Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: Workspace Proxy picker show latency to each proxy#7486

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Emyrk merged 23 commits intomainfromstevenmasley/proxy_picker
May 11, 2023
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
23 commits
Select commitHold shift + click to select a range
40ec420
WIP, this is a broken axios
EmyrkMay 9, 2023
d639a76
Discard intercepters
EmyrkMay 9, 2023
5f73d6b
Performance wip
EmyrkMay 10, 2023
bec803f
chore: Add cors to workspace proxies to allow for latency checks
EmyrkMay 10, 2023
4b7a40e
WUIP
EmyrkMay 10, 2023
3cae4b0
Add latency check to wsproxy
EmyrkMay 10, 2023
45d0e4c
wip
EmyrkMay 10, 2023
32d0e41
Wip
EmyrkMay 10, 2023
c2638ab
chore: Fix FE for measuring latencies
EmyrkMay 10, 2023
66399ae
Switch to proxy latency report
EmyrkMay 10, 2023
ce7ad2b
Fix cache bust busting our own cache
EmyrkMay 10, 2023
5c1412f
Share colors from the agent row
EmyrkMay 10, 2023
aab9e71
Merge remote-tracking branch 'origin/main' into stevenmasley/proxy_pi…
EmyrkMay 10, 2023
583ad65
Fix yarn deps?
EmyrkMay 10, 2023
77498b1
fmt
EmyrkMay 10, 2023
2cdb2a9
Fmt
EmyrkMay 11, 2023
bc1c10d
Add performance mock
EmyrkMay 11, 2023
bc38e40
nolint
EmyrkMay 11, 2023
679e5fc
Remove global mock
EmyrkMay 11, 2023
b90eda0
Add mock latencies to tests/storybook
EmyrkMay 11, 2023
3d8063e
Github actions was down, forcing it to run
EmyrkMay 11, 2023
56bf7b7
Merge remote-tracking branch 'origin/main' into stevenmasley/proxy_pi…
EmyrkMay 11, 2023
16699b6
skip flakey test
EmyrkMay 11, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletionscoderd/coderd.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -805,6 +805,17 @@ func New(options *Options) *API {
return []string{}
})
r.NotFound(cspMW(compressHandler(http.HandlerFunc(api.siteHandler.ServeHTTP))).ServeHTTP)

// This must be before all middleware to improve the response time.
// So make a new router, and mount the old one as the root.
rootRouter := chi.NewRouter()
// This is the only route we add before all the middleware.
// We want to time the latency of the request, so any middleware will
// interfere with that timing.
rootRouter.Get("/latency-check", LatencyCheck(api.AccessURL))
rootRouter.Mount("/", r)
api.RootHandler = rootRouter

return api
}

Expand Down
9 changes: 9 additions & 0 deletionscoderd/coderd_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,6 +124,15 @@ func TestDERPLatencyCheck(t *testing.T) {
require.Equal(t, http.StatusOK, res.StatusCode)
}

func TestFastLatencyCheck(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
res, err := client.Request(context.Background(), http.MethodGet, "/latency-check", nil)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
}

func TestHealthz(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
Expand Down
24 changes: 24 additions & 0 deletionscoderd/latencycheck.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
package coderd

import (
"net/http"
"net/url"
"strings"
)

func LatencyCheck(allowedOrigins ...*url.URL) http.HandlerFunc {
allowed := make([]string, 0, len(allowedOrigins))
for _, origin := range allowedOrigins {
// Allow the origin without a path
tmp := *origin
tmp.Path = ""
allowed = append(allowed, strings.TrimSuffix(origin.String(), "/"))
}
origins := strings.Join(allowed, ",")
return func(rw http.ResponseWriter, r *http.Request) {
// Allowing timing information to be shared. This allows the browser
// to exclude TLS handshake timing.
rw.Header().Set("Timing-Allow-Origin", origins)
rw.WriteHeader(http.StatusOK)
}
}
1 change: 1 addition & 0 deletionsenterprise/coderd/workspaceproxy_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -175,6 +175,7 @@ func TestRegions(t *testing.T) {
})

t.Run("GoingAway", func(t *testing.T) {
t.Skip("This is flakey in CI because it relies on internal go routine timing. Should refactor.")
t.Parallel()

dv := coderdtest.DeploymentValues(t)
Expand Down
38 changes: 24 additions & 14 deletionsenterprise/wsproxy/wsproxy.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ import (

"cdr.dev/slog"
"github.com/coder/coder/buildinfo"
"github.com/coder/coder/coderd"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/coderd/httpmw"
"github.com/coder/coder/coderd/tracing"
Expand DownExpand Up@@ -186,6 +187,21 @@ func New(ctx context.Context, opts *Options) (*Server, error) {
SecureAuthCookie: opts.SecureAuthCookie,
}

// The primary coderd dashboard needs to make some GET requests to
// the workspace proxies to check latency.
corsMW := cors.Handler(cors.Options{
AllowedOrigins: []string{
// Allow the dashboard to make requests to the proxy for latency
// checks.
opts.DashboardURL.String(),
},
// Only allow GET requests for latency checks.
AllowedMethods: []string{http.MethodOptions, http.MethodGet},
AllowedHeaders: []string{"Accept", "Content-Type", "X-LATENCY-CHECK", "X-CSRF-TOKEN"},
// Do not send any cookies
AllowCredentials: false,
})

// Routes
apiRateLimiter := httpmw.RateLimit(opts.APIRateLimit, time.Minute)
// Persistent middlewares to all routes
Expand All@@ -198,20 +214,7 @@ func New(ctx context.Context, opts *Options) (*Server, error) {
httpmw.ExtractRealIP(s.Options.RealIPConfig),
httpmw.Logger(s.Logger),
httpmw.Prometheus(s.PrometheusRegistry),
// The primary coderd dashboard needs to make some GET requests to
// the workspace proxies to check latency.
cors.Handler(cors.Options{
AllowedOrigins: []string{
// Allow the dashboard to make requests to the proxy for latency
// checks.
opts.DashboardURL.String(),
},
// Only allow GET requests for latency checks.
AllowedMethods: []string{http.MethodGet},
AllowedHeaders: []string{"Accept", "Content-Type"},
// Do not send any cookies
AllowCredentials: false,
}),
corsMW,

// HandleSubdomain is a middleware that handles all requests to the
// subdomain-based workspace apps.
Expand DownExpand Up@@ -260,6 +263,13 @@ func New(ctx context.Context, opts *Options) (*Server, error) {
})
})

// See coderd/coderd.go for why we need this.
rootRouter := chi.NewRouter()
// Make sure to add the cors middleware to the latency check route.
rootRouter.Get("/latency-check", corsMW(coderd.LatencyCheck(s.DashboardURL, s.AppServer.AccessURL)).ServeHTTP)
rootRouter.Mount("/", r)
s.Handler = rootRouter

return s, nil
}

Expand Down
24 changes: 24 additions & 0 deletionssite/jest.setup.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,9 +6,33 @@ import "jest-location-mock"
import { TextEncoder, TextDecoder } from "util"
import { Blob } from "buffer"
import jestFetchMock from "jest-fetch-mock"
import { ProxyLatencyReport } from "contexts/useProxyLatency"
import { RegionsResponse } from "api/typesGenerated"

jestFetchMock.enableMocks()

// useProxyLatency does some http requests to determine latency.
// This would fail unit testing, or at least make it very slow with
// actual network requests. So just globally mock this hook.
jest.mock("contexts/useProxyLatency", () => ({
useProxyLatency: (proxies?: RegionsResponse) => {
if (!proxies) {
return {} as Record<string, ProxyLatencyReport>
}

return proxies.regions.reduce((acc, proxy) => {
acc[proxy.id] = {
accurate: true,
// Return a constant latency of 8ms.
// If you make this random it could break stories.
latencyMS: 8,
at: new Date(),
}
return acc
}, {} as Record<string, ProxyLatencyReport>)
},
}))

global.TextEncoder = TextEncoder
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Polyfill for jsdom
global.TextDecoder = TextDecoder as any
Expand Down
1 change: 1 addition & 0 deletionssite/package.json
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,7 @@
"dependencies": {
"@emoji-mart/data": "1.0.5",
"@emoji-mart/react": "1.0.1",
"@fastly/performance-observer-polyfill": "^2.0.0",
"@emotion/react": "^11.10.8",
"@emotion/styled": "^11.10.8",
"@fontsource/ibm-plex-mono": "4.5.10",
Expand Down
2 changes: 2 additions & 0 deletionssite/src/components/AppLink/AppLink.stories.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@ import {
MockWorkspace,
MockWorkspaceAgent,
MockWorkspaceApp,
MockProxyLatencies,
} from "testHelpers/entities"
import { AppLink, AppLinkProps } from "./AppLink"
import { ProxyContext, getPreferredProxy } from "contexts/ProxyContext"
Expand All@@ -17,6 +18,7 @@ export default {
const Template: Story<AppLinkProps> = (args) => (
<ProxyContext.Provider
value={{
proxyLatencies: MockProxyLatencies,
proxy: getPreferredProxy(MockWorkspaceProxies, MockPrimaryWorkspaceProxy),
proxies: MockWorkspaceProxies,
isLoading: false,
Expand Down
13 changes: 3 additions & 10 deletionssite/src/components/Resources/AgentLatency.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
import { useRef, useState, FC } from "react"
import { makeStyles, useTheme } from "@mui/styles"
import { Theme } from "@mui/material/styles"
import {
HelpTooltipText,
HelpPopover,
HelpTooltipTitle,
} from "components/Tooltips/HelpTooltip"
import { Stack } from "components/Stack/Stack"
import { WorkspaceAgent, DERPRegion } from "api/typesGenerated"
import {Theme } from "@mui/material/styles"
import {getLatencyColor } from "utils/colors"

const getDisplayLatency = (theme: Theme, agent: WorkspaceAgent) => {
// Find the right latency to display
Expand All@@ -22,17 +23,9 @@ const getDisplayLatency = (theme: Theme, agent: WorkspaceAgent) => {
return undefined
}

// Get the color
let color = theme.palette.success.light
if (latency.latency_ms >= 150 && latency.latency_ms < 300) {
color = theme.palette.warning.light
} else if (latency.latency_ms >= 300) {
color = theme.palette.error.light
}

return {
...latency,
color,
color: getLatencyColor(theme, latency.latency_ms),
}
}

Expand Down
2 changes: 2 additions & 0 deletionssite/src/components/Resources/AgentRow.stories.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@ import {
MockWorkspaceAgentStartTimeout,
MockWorkspaceAgentTimeout,
MockWorkspaceApp,
MockProxyLatencies,
} from "testHelpers/entities"
import { AgentRow, AgentRowProps } from "./AgentRow"
import { ProxyContext, getPreferredProxy } from "contexts/ProxyContext"
Expand DownExpand Up@@ -56,6 +57,7 @@ const TemplateFC = (
return (
<ProxyContext.Provider
value={{
proxyLatencies: MockProxyLatencies,
proxy: getPreferredProxy(proxies, selectedProxy),
proxies: proxies,
isLoading: false,
Expand Down
8 changes: 7 additions & 1 deletionsite/src/components/Resources/ResourceCard.stories.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
import { action } from "@storybook/addon-actions"
import { Story } from "@storybook/react"
import { MockWorkspace, MockWorkspaceResource } from "testHelpers/entities"
import {
MockProxyLatencies,
MockWorkspace,
MockWorkspaceResource,
} from "testHelpers/entities"
import { AgentRow } from "./AgentRow"
import { ResourceCard, ResourceCardProps } from "./ResourceCard"
import { ProxyContext, getPreferredProxy } from "contexts/ProxyContext"
Expand All@@ -18,6 +22,7 @@ Example.args = {
agentRow: (agent) => (
<ProxyContext.Provider
value={{
proxyLatencies: MockProxyLatencies,
proxy: getPreferredProxy([], undefined),
proxies: [],
isLoading: false,
Expand DownExpand Up@@ -84,6 +89,7 @@ BunchOfMetadata.args = {
agentRow: (agent) => (
<ProxyContext.Provider
value={{
proxyLatencies: MockProxyLatencies,
proxy: getPreferredProxy([], undefined),
proxies: [],
isLoading: false,
Expand Down
2 changes: 2 additions & 0 deletionssite/src/components/Workspace/Workspace.stories.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@ import { Workspace, WorkspaceErrors, WorkspaceProps } from "./Workspace"
import { withReactContext } from "storybook-react-context"
import EventSource from "eventsourcemock"
import { ProxyContext, getPreferredProxy } from "contexts/ProxyContext"
import { MockProxyLatencies } from "../../testHelpers/entities"

export default {
title: "components/Workspace",
Expand All@@ -26,6 +27,7 @@ export default {
const Template: Story<WorkspaceProps> = (args) => (
<ProxyContext.Provider
value={{
proxyLatencies: MockProxyLatencies,
proxy: getPreferredProxy([], undefined),
proxies: [],
isLoading: false,
Expand Down
7 changes: 7 additions & 0 deletionssite/src/contexts/ProxyContext.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,10 +9,12 @@ import {
useContext,
useState,
} from "react"
import { ProxyLatencyReport, useProxyLatency } from "./useProxyLatency"

interface ProxyContextValue {
proxy: PreferredProxy
proxies?: Region[]
proxyLatencies?: Record<string, ProxyLatencyReport>
// isfetched is true when the proxy api call is complete.
isFetched: boolean
// isLoading is true if the proxy is in the process of being fetched.
Expand DownExpand Up@@ -72,6 +74,10 @@ export const ProxyProvider: FC<PropsWithChildren> = ({ children }) => {
},
})

// Everytime we get a new proxiesResponse, update the latency check
// to each workspace proxy.
const proxyLatencies = useProxyLatency(proxiesResp)

const setAndSaveProxy = (
selectedProxy?: Region,
// By default the proxies come from the api call above.
Expand All@@ -95,6 +101,7 @@ export const ProxyProvider: FC<PropsWithChildren> = ({ children }) => {
return (
<ProxyContext.Provider
value={{
proxyLatencies: proxyLatencies,
proxy: experimentEnabled
? proxy
: {
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp