Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
32 changes: 23 additions & 9 deletions coderd/autobuild/lifecycle_executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"errors"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -1720,19 +1721,32 @@ func TestExecutorAutostartSkipsWhenNoProvisionersAvailable(t *testing.T) {
// Stop the workspace while provisioner is available
workspace = coderdtest.MustTransitionWorkspace(t, client, workspace.ID, codersdk.WorkspaceTransitionStart, codersdk.WorkspaceTransitionStop)

// Wait for provisioner to be available for this specific workspace
coderdtest.MustWaitForProvisionersAvailable(t, db, workspace)
p, err := coderdtest.GetProvisionerForTags(db, time.Now(), workspace.OrganizationID, provisionerDaemonTags)
require.NoError(t, err, "Error getting provisioner for workspace")

daemon1Closer.Close()
var wg sync.WaitGroup
wg.Add(2)

// Ensure the provisioner is stale
staleTime := sched.Next(workspace.LatestBuild.CreatedAt).Add((-1 * provisionerdserver.StaleInterval) + -10*time.Second)
coderdtest.UpdateProvisionerLastSeenAt(t, db, p.ID, staleTime)
next := sched.Next(workspace.LatestBuild.CreatedAt)
go func() {
defer wg.Done()
// Ensure the provisioner is stale
staleTime := next.Add(-(provisionerdserver.StaleInterval * 2))
coderdtest.UpdateProvisionerLastSeenAt(t, db, p.ID, staleTime)
p, err = coderdtest.GetProvisionerForTags(db, time.Now(), workspace.OrganizationID, provisionerDaemonTags)
assert.NoError(t, err, "Error getting provisioner for workspace")
assert.Eventually(t, func() bool { return p.LastSeenAt.Time.UnixNano() == staleTime.UnixNano() }, testutil.WaitMedium, testutil.IntervalFast)
}()

// Trigger autobuild
tickCh <- sched.Next(workspace.LatestBuild.CreatedAt)
go func() {
defer wg.Done()
// Ensure the provisioner is gone or stale before triggering the autobuild
coderdtest.MustWaitForProvisionersUnavailable(t, db, workspace, provisionerDaemonTags, next)
// Trigger autobuild
tickCh <- next
}()

wg.Wait()

stats := <-statsCh

Expand All @@ -1758,5 +1772,5 @@ func TestExecutorAutostartSkipsWhenNoProvisionersAvailable(t *testing.T) {
}()
stats = <-statsCh

assert.Len(t, stats.Transitions, 1, "should not create builds when no provisioners available")
assert.Len(t, stats.Transitions, 1, "should create builds when provisioners are available")
}
44 changes: 36 additions & 8 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -1649,19 +1649,48 @@ func UpdateProvisionerLastSeenAt(t *testing.T, db database.Store, id uuid.UUID,
func MustWaitForAnyProvisioner(t *testing.T, db database.Store) {
t.Helper()
ctx := ctxWithProvisionerPermissions(testutil.Context(t, testutil.WaitShort))
require.Eventually(t, func() bool {
// testutil.Eventually(t, func)
testutil.Eventually(ctx, t, func(ctx context.Context) (done bool) {
daemons, err := db.GetProvisionerDaemons(ctx)
return err == nil && len(daemons) > 0
}, testutil.WaitShort, testutil.IntervalFast)
}, testutil.IntervalFast, "no provisioner daemons found")
}

// MustWaitForProvisionersUnavailable waits for provisioners to become unavailable for a specific workspace
func MustWaitForProvisionersUnavailable(t *testing.T, db database.Store, workspace codersdk.Workspace, tags map[string]string, checkTime time.Time) {
t.Helper()
ctx := ctxWithProvisionerPermissions(testutil.Context(t, testutil.WaitMedium))

testutil.Eventually(ctx, t, func(ctx context.Context) (done bool) {
// Use the same logic as hasValidProvisioner but expect false
provisionerDaemons, err := db.GetProvisionerDaemonsByOrganization(ctx, database.GetProvisionerDaemonsByOrganizationParams{
OrganizationID: workspace.OrganizationID,
WantTags: tags,
})
if err != nil {
return false
}

// Check if NO provisioners are active (all are stale or gone)
for _, pd := range provisionerDaemons {
if pd.LastSeenAt.Valid {
age := checkTime.Sub(pd.LastSeenAt.Time)
if age <= provisionerdserver.StaleInterval {
return false // Found an active provisioner, keep waiting
}
}
}
return true // No active provisioners found
}, testutil.IntervalFast, "there are still provisioners available for workspace, expected none")
}

// MustWaitForProvisionersAvailable waits for provisioners to be available for a specific workspace.
func MustWaitForProvisionersAvailable(t *testing.T, db database.Store, workspace codersdk.Workspace) uuid.UUID {
func MustWaitForProvisionersAvailable(t *testing.T, db database.Store, workspace codersdk.Workspace, ts time.Time) uuid.UUID {
t.Helper()
ctx := ctxWithProvisionerPermissions(testutil.Context(t, testutil.WaitShort))
ctx := ctxWithProvisionerPermissions(testutil.Context(t, testutil.WaitLong))
id := uuid.UUID{}
// Get the workspace from the database
require.Eventually(t, func() bool {
testutil.Eventually(ctx, t, func(ctx context.Context) (done bool) {
ws, err := db.GetWorkspaceByID(ctx, workspace.ID)
if err != nil {
return false
Expand Down Expand Up @@ -1689,18 +1718,17 @@ func MustWaitForProvisionersAvailable(t *testing.T, db database.Store, workspace
}

// Check if any provisioners are active (not stale)
now := time.Now()
for _, pd := range provisionerDaemons {
if pd.LastSeenAt.Valid {
age := now.Sub(pd.LastSeenAt.Time)
age := ts.Sub(pd.LastSeenAt.Time)
if age <= provisionerdserver.StaleInterval {
id = pd.ID
return true // Found an active provisioner
}
}
}
return false // No active provisioners found
}, testutil.WaitLong, testutil.IntervalFast)
}, testutil.IntervalFast, "no active provisioners available for workspace, expected at least one (non-stale)")

return id
}
7 changes: 4 additions & 3 deletions enterprise/coderd/workspaces_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2242,13 +2242,14 @@ func TestPrebuildsAutobuild(t *testing.T) {
workspace = coderdtest.MustTransitionWorkspace(t, client, workspace.ID, codersdk.WorkspaceTransitionStart, codersdk.WorkspaceTransitionStop)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)

p, err := coderdtest.GetProvisionerForTags(db, time.Now(), workspace.OrganizationID, nil)
coderdtest.UpdateProvisionerLastSeenAt(t, db, p.ID, sched.Next(prebuild.LatestBuild.CreatedAt))

// Wait for provisioner to be available for this specific workspace
coderdtest.MustWaitForProvisionersAvailable(t, db, prebuild)
coderdtest.MustWaitForProvisionersAvailable(t, db, prebuild, sched.Next(prebuild.LatestBuild.CreatedAt))

tickTime := sched.Next(prebuild.LatestBuild.CreatedAt).Add(time.Minute)
p, err := coderdtest.GetProvisionerForTags(db, time.Now(), workspace.OrganizationID, nil)
require.NoError(t, err)
coderdtest.UpdateProvisionerLastSeenAt(t, db, p.ID, tickTime)

// Tick at the next scheduled time after the prebuild’s LatestBuild.CreatedAt,
// since the next allowed autostart is calculated starting from that point.
Expand Down
2 changes: 2 additions & 0 deletions site/src/components/Filter/UserFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { useAuthenticated } from "hooks";
import type { FC } from "react";
import { type UseFilterMenuOptions, useFilterMenu } from "./menu";

export const DEFAULT_USER_FILTER_WIDTH = 175;

export const useUserFilterMenu = ({
value,
onChange,
Expand Down
9 changes: 6 additions & 3 deletions site/src/pages/AuditPage/AuditFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import {
SelectFilter,
type SelectFilterOption,
} from "components/Filter/SelectFilter";
import { type UserFilterMenu, UserMenu } from "components/Filter/UserFilter";
import {
DEFAULT_USER_FILTER_WIDTH,
type UserFilterMenu,
UserMenu,
} from "components/Filter/UserFilter";
import capitalize from "lodash/capitalize";
import {
type OrganizationsFilterMenu,
Expand Down Expand Up @@ -47,8 +51,7 @@ interface AuditFilterProps {
}

export const AuditFilter: FC<AuditFilterProps> = ({ filter, error, menus }) => {
const width = menus.organization ? 175 : undefined;

const width = menus.organization ? DEFAULT_USER_FILTER_WIDTH : undefined;
return (
<Filter
learnMoreLink={docs("/admin/security/audit-logs#filtering-logs")}
Expand Down
9 changes: 6 additions & 3 deletions site/src/pages/ConnectionLogPage/ConnectionLogFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import {
SelectFilter,
type SelectFilterOption,
} from "components/Filter/SelectFilter";
import { type UserFilterMenu, UserMenu } from "components/Filter/UserFilter";
import {
DEFAULT_USER_FILTER_WIDTH,
type UserFilterMenu,
UserMenu,
} from "components/Filter/UserFilter";
import capitalize from "lodash/capitalize";
import {
type OrganizationsFilterMenu,
Expand Down Expand Up @@ -42,8 +46,7 @@ export const ConnectionLogFilter: FC<ConnectionLogFilterProps> = ({
error,
menus,
}) => {
const width = menus.organization ? 175 : undefined;

const width = menus.organization ? DEFAULT_USER_FILTER_WIDTH : undefined;
return (
<Filter
learnMoreLink={docs(
Expand Down
43 changes: 33 additions & 10 deletions site/src/pages/TemplatesPage/TemplatesFilter.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,38 @@
import { API } from "api/api";
import type { Organization } from "api/typesGenerated";
import { Avatar } from "components/Avatar/Avatar";
import { Filter, MenuSkeleton, type useFilter } from "components/Filter/Filter";
import {
Filter,
MenuSkeleton,
type UseFilterResult,
} from "components/Filter/Filter";
import { useFilterMenu } from "components/Filter/menu";
import {
SelectFilter,
type SelectFilterOption,
} from "components/Filter/SelectFilter";
import { useDashboard } from "modules/dashboard/useDashboard";
import type { FC } from "react";
import {
DEFAULT_USER_FILTER_WIDTH,
type UserFilterMenu,
UserMenu,
} from "../../components/Filter/UserFilter";

interface TemplatesFilterProps {
filter: ReturnType<typeof useFilter>;
filter: UseFilterResult;
error?: unknown;

userMenu?: UserFilterMenu;
}

export const TemplatesFilter: FC<TemplatesFilterProps> = ({
filter,
error,
userMenu,
}) => {
const { showOrganizations } = useDashboard();
const width = showOrganizations ? DEFAULT_USER_FILTER_WIDTH : undefined;
const organizationMenu = useFilterMenu({
onChange: (option) =>
filter.update({ ...filter.values, organization: option?.value }),
Expand Down Expand Up @@ -50,15 +65,23 @@ export const TemplatesFilter: FC<TemplatesFilterProps> = ({
filter={filter}
error={error}
options={
<SelectFilter
placeholder="All organizations"
label="Select an organization"
options={organizationMenu.searchOptions}
selectedOption={organizationMenu.selectedOption ?? undefined}
onSelect={organizationMenu.selectOption}
/>
<>
{userMenu && <UserMenu width={width} menu={userMenu} />}
<SelectFilter
placeholder="All organizations"
label="Select an organization"
options={organizationMenu.searchOptions}
selectedOption={organizationMenu.selectedOption ?? undefined}
onSelect={organizationMenu.selectOption}
/>
</>
}
optionsSkeleton={
<>
{userMenu && <MenuSkeleton />}
<MenuSkeleton />
</>
}
optionsSkeleton={<MenuSkeleton />}
/>
);
};
Expand Down
50 changes: 44 additions & 6 deletions site/src/pages/TemplatesPage/TemplatesPage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { workspacePermissionsByOrganization } from "api/queries/organizations";
import { templateExamples, templates } from "api/queries/templates";
import { useFilter } from "components/Filter/Filter";
import { type UseFilterResult, useFilter } from "components/Filter/Filter";
import { useUserFilterMenu } from "components/Filter/UserFilter";
import { useAuthenticated } from "hooks";
import { useDashboard } from "modules/dashboard/useDashboard";
import type { FC } from "react";
Expand All @@ -15,14 +16,12 @@ const TemplatesPage: FC = () => {
const { showOrganizations } = useDashboard();

const [searchParams, setSearchParams] = useSearchParams();
const filter = useFilter({
fallbackFilter: "deprecated:false",
const filterState = useTemplatesFilter({
searchParams,
onSearchParamsChange: setSearchParams,
onUpdate: () => {}, // reset pagination
});

const templatesQuery = useQuery(templates({ q: filter.query }));
const templatesQuery = useQuery(templates({ q: filterState.filter.query }));
const examplesQuery = useQuery({
...templateExamples(),
enabled: permissions.createTemplates,
Expand All @@ -47,7 +46,7 @@ const TemplatesPage: FC = () => {
</Helmet>
<TemplatesPageView
error={error}
filter={filter}
filterState={filterState}
showOrganizations={showOrganizations}
canCreateTemplates={permissions.createTemplates}
examples={examplesQuery.data}
Expand All @@ -59,3 +58,42 @@ const TemplatesPage: FC = () => {
};

export default TemplatesPage;

export type TemplateFilterState = {
filter: UseFilterResult;
menus: {
user?: ReturnType<typeof useUserFilterMenu>;
};
};

type UseTemplatesFilterOptions = {
searchParams: URLSearchParams;
onSearchParamsChange: (params: URLSearchParams) => void;
};

const useTemplatesFilter = ({
searchParams,
onSearchParamsChange,
}: UseTemplatesFilterOptions): TemplateFilterState => {
const filter = useFilter({
fallbackFilter: "deprecated:false",
searchParams,
onSearchParamsChange,
});

const { permissions } = useAuthenticated();
const canFilterByUser = permissions.viewAllUsers;
const userMenu = useUserFilterMenu({
value: filter.values.author,
onChange: (option) =>
filter.update({ ...filter.values, author: option?.value }),
enabled: canFilterByUser,
});

return {
filter,
menus: {
user: canFilterByUser ? userMenu : undefined,
},
};
};
Loading
Loading