2022-01-25 13:52:58 -06:00
package coderd
import (
2022-04-25 16:11:03 -05:00
"context"
2022-01-25 13:52:58 -06:00
"database/sql"
2022-03-07 11:40:54 -06:00
"encoding/json"
2022-01-25 13:52:58 -06:00
"errors"
"fmt"
"net/http"
2024-06-14 10:08:45 -04:00
"slices"
2022-05-20 00:29:10 +10:00
"strconv"
2022-05-18 16:16:26 -05:00
"time"
2022-01-25 13:52:58 -06:00
2024-08-19 15:49:47 -03:00
"github.com/dustin/go-humanize"
2022-03-07 11:40:54 -06:00
"github.com/go-chi/chi/v5"
2022-01-25 13:52:58 -06:00
"github.com/google/uuid"
2025-03-31 10:55:44 -04:00
"golang.org/x/sync/errgroup"
2022-03-07 11:40:54 -06:00
"golang.org/x/xerrors"
2022-05-18 16:16:26 -05:00
"cdr.dev/slog"
2025-04-24 09:39:38 -04:00
2024-06-14 10:08:45 -04:00
"github.com/coder/coder/v2/agent/proto"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
2023-11-08 23:24:56 -06:00
"github.com/coder/coder/v2/coderd/database/db2sdk"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/database/dbauthz"
2023-09-01 19:50:12 +03:00
"github.com/coder/coder/v2/coderd/database/dbtime"
2023-09-19 10:25:57 +04:00
"github.com/coder/coder/v2/coderd/database/provisionerjobs"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/httpapi"
2025-06-23 15:08:18 -05:00
"github.com/coder/coder/v2/coderd/httpapi/httperror"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/httpmw"
2024-07-29 11:20:04 -03:00
"github.com/coder/coder/v2/coderd/notifications"
2025-04-24 09:39:38 -04:00
"github.com/coder/coder/v2/coderd/prebuilds"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/rbac"
2025-08-07 10:14:58 -06:00
"github.com/coder/coder/v2/coderd/rbac/acl"
2024-05-15 09:46:35 -05:00
"github.com/coder/coder/v2/coderd/rbac/policy"
2024-12-02 21:02:36 +00:00
"github.com/coder/coder/v2/coderd/schedule"
2023-09-04 16:48:25 +03:00
"github.com/coder/coder/v2/coderd/schedule/cron"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/searchquery"
"github.com/coder/coder/v2/coderd/telemetry"
"github.com/coder/coder/v2/coderd/util/ptr"
"github.com/coder/coder/v2/coderd/wsbuilder"
2024-11-01 14:17:05 +11:00
"github.com/coder/coder/v2/coderd/wspubsub"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
2022-01-25 13:52:58 -06:00
)
2022-07-29 15:01:17 +01:00
var (
2025-08-07 11:00:31 +10:00
ttlMinimum = time . Minute
ttlMaximum = 30 * 24 * time . Hour
2022-07-29 15:01:17 +01:00
2022-11-09 14:36:25 -05:00
errTTLMin = xerrors . New ( "time until shutdown must be at least one minute" )
2023-07-19 23:43:10 +10:00
errTTLMax = xerrors . New ( "time until shutdown must be less than 30 days" )
2022-11-09 14:36:25 -05:00
errDeadlineTooSoon = xerrors . New ( "new deadline must be at least 30 minutes in the future" )
errDeadlineBeforeStart = xerrors . New ( "new deadline must be before workspace start time" )
2022-07-29 15:01:17 +01:00
)
2022-12-19 18:43:46 +01:00
// @Summary Get workspace metadata by ID
// @ID get-workspace-metadata-by-id
// @Security CoderSessionToken
// @Produce json
// @Tags Workspaces
2023-01-13 12:27:21 +01:00
// @Param workspace path string true "Workspace ID" format(uuid)
2022-12-19 18:43:46 +01:00
// @Param include_deleted query bool false "Return data instead of HTTP 404 if the workspace is deleted"
// @Success 200 {object} codersdk.Workspace
2023-01-13 12:27:21 +01:00
// @Router /workspaces/{workspace} [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) workspace ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-03-07 11:40:54 -06:00
workspace := httpmw . WorkspaceParam ( r )
2024-01-24 13:39:19 +00:00
apiKey := httpmw . APIKey ( r )
2022-05-20 00:29:10 +10:00
var (
2022-06-10 09:58:42 -05:00
deletedStr = r . URL . Query (). Get ( "include_deleted" )
2022-05-20 00:29:10 +10:00
showDeleted = false
)
if deletedStr != "" {
var err error
showDeleted , err = strconv . ParseBool ( deletedStr )
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-10 09:58:42 -05:00
Message : fmt . Sprintf ( "Invalid boolean value %q for \"include_deleted\" query param." , deletedStr ),
2022-07-12 19:15:02 -05:00
Validations : [] codersdk . ValidationError {
2022-06-03 16:48:09 -05:00
{ Field : "deleted" , Detail : "Must be a valid boolean" },
},
2022-05-20 00:29:10 +10:00
})
return
}
}
if workspace . Deleted && ! showDeleted {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusGone , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : fmt . Sprintf ( "Workspace %q was deleted, you can view this workspace by specifying '?deleted=true' and trying again." , workspace . ID . String ()),
2022-05-20 00:29:10 +10:00
})
return
}
2022-09-21 17:07:00 -05:00
data , err := api . workspaceData ( ctx , [] database . Workspace { workspace })
2022-03-22 13:17:50 -06:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-09-16 14:54:23 -04:00
Message : "Internal error fetching workspace resources." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-03-22 13:17:50 -06:00
})
return
}
2022-05-13 20:41:21 -05:00
2023-08-17 13:22:03 -05:00
if len ( data . templates ) == 0 {
httpapi . Forbidden ( rw )
return
}
2024-01-24 14:13:14 +00:00
2025-03-31 10:55:44 -04:00
appStatus := codersdk . WorkspaceAppStatus {}
if len ( data . appStatuses ) > 0 {
appStatus = data . appStatuses [ 0 ]
}
2024-01-24 14:13:14 +00:00
w , err := convertWorkspace (
2024-01-24 13:39:19 +00:00
apiKey . UserID ,
2022-09-16 14:54:23 -04:00
workspace ,
data . builds [ 0 ],
data . templates [ 0 ],
2023-12-15 13:38:47 -05:00
api . Options . AllowWorkspaceRenames ,
2025-03-31 10:55:44 -04:00
appStatus ,
2024-01-24 14:13:14 +00:00
)
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error converting workspace." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusOK , w )
2022-03-07 11:40:54 -06:00
}
2023-01-13 12:27:21 +01:00
// workspaces returns all workspaces a user can read.
// Optional filters with query params
//
2022-12-19 18:43:46 +01:00
// @Summary List workspaces
2023-01-13 12:27:21 +01:00
// @ID list-workspaces
2022-12-19 18:43:46 +01:00
// @Security CoderSessionToken
// @Produce json
// @Tags Workspaces
2025-06-18 18:22:45 +02:00
// @Param q query string false "Search query in the format `key:value`. Available keys are: owner, template, name, status, has-agent, dormant, last_used_after, last_used_before, has-ai-task."
2023-07-10 13:57:09 -05:00
// @Param limit query int false "Page limit"
// @Param offset query int false "Page offset"
2022-12-19 18:43:46 +01:00
// @Success 200 {object} codersdk.WorkspacesResponse
// @Router /workspaces [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) workspaces ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-05-18 10:09:07 -05:00
apiKey := httpmw . APIKey ( r )
2022-05-16 14:36:27 -05:00
2025-07-15 14:55:34 +10:00
page , ok := ParsePagination ( rw , r )
2022-10-13 12:41:13 -04:00
if ! ok {
return
}
2022-06-14 08:46:33 -05:00
queryStr := r . URL . Query (). Get ( "q" )
2024-08-28 15:18:45 -05:00
filter , errs := searchquery . Workspaces ( ctx , api . Database , queryStr , page , api . AgentInactiveDisconnectTimeout )
2022-06-14 08:46:33 -05:00
if len ( errs ) > 0 {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-14 08:46:33 -05:00
Message : "Invalid workspace search query." ,
Validations : errs ,
})
return
}
2022-05-18 10:09:07 -05:00
2022-06-14 08:46:33 -05:00
if filter . OwnerUsername == "me" {
2022-05-18 10:09:07 -05:00
filter . OwnerID = apiKey . UserID
2022-06-14 08:46:33 -05:00
filter . OwnerUsername = ""
2022-05-18 10:09:07 -05:00
}
2022-11-28 12:12:34 -06:00
// Workspaces do not have ACL columns.
2024-05-15 09:46:35 -05:00
prepared , err := api . HTTPAuth . AuthorizeSQLFilter ( r , policy . ActionRead , rbac . ResourceWorkspace . Type )
2022-05-16 14:36:27 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-10-04 11:35:33 -04:00
Message : "Internal error preparing sql filter." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2024-01-24 13:39:19 +00:00
// To show the requester's favorite workspaces first, we pass their userID and compare it to
// the workspace owner_id when ordering the rows.
filter . RequesterID = apiKey . UserID
2024-03-05 09:24:43 +01:00
// We need the technical row to present the correct count on every page.
filter . WithSummary = true
2022-11-28 12:12:34 -06:00
workspaceRows , err := api . Database . GetAuthorizedWorkspaces ( ctx , filter , prepared )
2022-08-11 17:07:48 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-08-11 17:07:48 -05:00
Message : "Internal error fetching workspaces." ,
Detail : err . Error (),
})
return
}
2024-03-05 09:24:43 +01:00
if len ( workspaceRows ) == 0 {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching workspaces." ,
Detail : "Workspace summary row is missing." ,
})
return
}
if len ( workspaceRows ) == 1 {
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . WorkspacesResponse {
Workspaces : [] codersdk . Workspace {},
Count : int ( workspaceRows [ 0 ]. Count ),
})
return
}
// Skip technical summary row
workspaceRows = workspaceRows [: len ( workspaceRows ) - 1 ]
2022-11-16 10:16:37 -05:00
if len ( workspaceRows ) == 0 {
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . WorkspacesResponse {
Workspaces : [] codersdk . Workspace {},
Count : 0 ,
})
return
}
2022-05-24 08:43:34 -05:00
2022-11-16 10:16:37 -05:00
workspaces := database . ConvertWorkspaceRows ( workspaceRows )
2022-11-10 13:25:46 -05:00
2022-09-21 17:07:00 -05:00
data , err := api . workspaceData ( ctx , workspaces )
2022-05-16 14:36:27 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-09-16 14:54:23 -04:00
Message : "Internal error fetching workspace resources." ,
2022-06-07 09:33:06 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2022-09-16 14:54:23 -04:00
2024-01-24 13:39:19 +00:00
wss , err := convertWorkspaces ( apiKey . UserID , workspaces , data )
2022-09-16 14:54:23 -04:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-09-16 14:54:23 -04:00
Message : "Internal error converting workspaces." ,
Detail : err . Error (),
})
return
}
2022-11-10 13:25:46 -05:00
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . WorkspacesResponse {
2023-10-10 19:00:09 -05:00
Workspaces : wss ,
2022-11-16 10:16:37 -05:00
Count : int ( workspaceRows [ 0 ]. Count ),
2022-10-20 13:23:14 -04:00
})
}
2023-01-11 14:08:04 +01:00
// @Summary Get workspace metadata by user and workspace name
// @ID get-workspace-metadata-by-user-and-workspace-name
2022-12-19 18:43:46 +01:00
// @Security CoderSessionToken
// @Produce json
// @Tags Workspaces
2023-01-11 14:08:04 +01:00
// @Param user path string true "User ID, name, or me"
2022-12-19 18:43:46 +01:00
// @Param workspacename path string true "Workspace name"
// @Param include_deleted query bool false "Return data instead of HTTP 404 if the workspace is deleted"
// @Success 200 {object} codersdk.Workspace
// @Router /users/{user}/workspace/{workspacename} [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) workspaceByOwnerAndName ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2025-05-08 14:41:17 -05:00
mems := httpmw . OrganizationMembersParam ( r )
2022-05-18 18:15:19 -05:00
workspaceName := chi . URLParam ( r , "workspacename" )
2024-01-24 13:39:19 +00:00
apiKey := httpmw . APIKey ( r )
2022-05-16 14:36:27 -05:00
2022-06-08 14:04:05 -04:00
includeDeleted := false
if s := r . URL . Query (). Get ( "include_deleted" ); s != "" {
var err error
includeDeleted , err = strconv . ParseBool ( s )
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-08 14:04:05 -04:00
Message : fmt . Sprintf ( "Invalid boolean value %q for \"include_deleted\" query param." , s ),
2022-07-12 19:15:02 -05:00
Validations : [] codersdk . ValidationError {
2022-06-08 14:04:05 -04:00
{ Field : "include_deleted" , Detail : "Must be a valid boolean" },
},
})
return
}
}
2022-09-21 17:07:00 -05:00
workspace , err := api . Database . GetWorkspaceByOwnerIDAndName ( ctx , database . GetWorkspaceByOwnerIDAndNameParams {
2025-05-08 14:41:17 -05:00
OwnerID : mems . UserID (),
2022-05-16 14:36:27 -05:00
Name : workspaceName ,
})
2022-06-08 14:04:05 -04:00
if includeDeleted && errors . Is ( err , sql . ErrNoRows ) {
2022-09-21 17:07:00 -05:00
workspace , err = api . Database . GetWorkspaceByOwnerIDAndName ( ctx , database . GetWorkspaceByOwnerIDAndNameParams {
2025-05-08 14:41:17 -05:00
OwnerID : mems . UserID (),
2022-06-08 14:04:05 -04:00
Name : workspaceName ,
Deleted : includeDeleted ,
})
}
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2022-06-14 10:14:05 -05:00
httpapi . ResourceNotFound ( rw )
2022-05-16 14:36:27 -05:00
return
}
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching workspace by name." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2022-05-17 13:43:19 -05:00
2022-09-21 17:07:00 -05:00
data , err := api . workspaceData ( ctx , [] database . Workspace { workspace })
2022-05-16 14:36:27 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-09-16 14:54:23 -04:00
Message : "Internal error fetching workspace resources." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2023-03-10 12:26:11 +01:00
if len ( data . builds ) == 0 || len ( data . templates ) == 0 {
httpapi . ResourceNotFound ( rw )
return
}
2024-10-22 09:20:54 -05:00
2025-03-31 10:55:44 -04:00
appStatus := codersdk . WorkspaceAppStatus {}
if len ( data . appStatuses ) > 0 {
appStatus = data . appStatuses [ 0 ]
}
2024-01-24 14:13:14 +00:00
w , err := convertWorkspace (
2024-01-24 13:39:19 +00:00
apiKey . UserID ,
2022-09-16 14:54:23 -04:00
workspace ,
data . builds [ 0 ],
data . templates [ 0 ],
2023-12-15 13:38:47 -05:00
api . Options . AllowWorkspaceRenames ,
2025-03-31 10:55:44 -04:00
appStatus ,
2024-01-24 14:13:14 +00:00
)
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error converting workspace." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusOK , w )
2022-05-16 14:36:27 -05:00
}
2023-01-13 12:27:21 +01:00
// Create a new workspace for the currently authenticated user.
//
2023-01-11 12:16:09 +01:00
// @Summary Create user workspace by organization
2024-04-02 10:11:24 -05:00
// @Description Create a new workspace using a template. The request must
// @Description specify either the Template ID or the Template Version ID,
// @Description not both. If the Template ID is specified, the active version
// @Description of the template will be used.
2024-07-30 10:44:02 -06:00
// @Deprecated Use /users/{user}/workspaces instead.
2023-01-11 12:16:09 +01:00
// @ID create-user-workspace-by-organization
2022-12-19 18:43:46 +01:00
// @Security CoderSessionToken
2023-02-09 15:02:03 +01:00
// @Accept json
2022-12-19 18:43:46 +01:00
// @Produce json
// @Tags Workspaces
// @Param organization path string true "Organization ID" format(uuid)
2023-01-11 12:16:09 +01:00
// @Param user path string true "Username, UUID, or me"
2023-02-09 15:02:03 +01:00
// @Param request body codersdk.CreateWorkspaceRequest true "Create workspace request"
2022-12-19 18:43:46 +01:00
// @Success 200 {object} codersdk.Workspace
// @Router /organizations/{organization}/members/{user}/workspaces [post]
2022-05-25 22:14:08 -05:00
func ( api * API ) postWorkspacesByOrganization ( rw http . ResponseWriter , r * http . Request ) {
2022-09-10 11:07:45 -05:00
var (
2023-01-30 13:43:29 -05:00
ctx = r . Context ()
apiKey = httpmw . APIKey ( r )
auditor = api . Auditor . Load ()
2024-07-30 10:44:02 -06:00
organization = httpmw . OrganizationParam ( r )
2023-10-11 09:41:14 +04:00
member = httpmw . OrganizationMemberParam ( r )
2023-01-30 13:43:29 -05:00
workspaceResourceInfo = audit . AdditionalFields {
2023-10-11 09:41:14 +04:00
WorkspaceOwner : member . Username ,
2023-01-30 13:43:29 -05:00
}
2022-09-10 11:07:45 -05:00
)
2022-12-09 12:19:30 -05:00
2024-10-22 09:20:54 -05:00
aReq , commitAudit := audit . InitRequest [ database . WorkspaceTable ]( rw , & audit . RequestParams {
2023-01-30 13:43:29 -05:00
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionCreate ,
2024-06-20 17:22:27 -05:00
AdditionalFields : workspaceResourceInfo ,
2024-02-26 08:27:33 -06:00
OrganizationID : organization . ID ,
2023-01-30 13:43:29 -05:00
})
2022-09-10 11:07:45 -05:00
defer commitAudit ()
2024-07-30 10:44:02 -06:00
var req codersdk . CreateWorkspaceRequest
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-05-16 14:36:27 -05:00
return
}
2022-05-27 11:19:13 -05:00
2024-07-30 10:44:02 -06:00
owner := workspaceOwner {
ID : member . UserID ,
Username : member . Username ,
AvatarURL : member . AvatarURL ,
}
createWorkspace ( ctx , aReq , apiKey . UserID , api , owner , req , rw , r )
}
// Create a new workspace for the currently authenticated user.
//
// @Summary Create user workspace
// @Description Create a new workspace using a template. The request must
// @Description specify either the Template ID or the Template Version ID,
// @Description not both. If the Template ID is specified, the active version
// @Description of the template will be used.
// @ID create-user-workspace
// @Security CoderSessionToken
// @Accept json
// @Produce json
// @Tags Workspaces
// @Param user path string true "Username, UUID, or me"
// @Param request body codersdk.CreateWorkspaceRequest true "Create workspace request"
// @Success 200 {object} codersdk.Workspace
// @Router /users/{user}/workspaces [post]
func ( api * API ) postUserWorkspaces ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
apiKey = httpmw . APIKey ( r )
auditor = api . Auditor . Load ()
2025-05-08 14:41:17 -05:00
mems = httpmw . OrganizationMembersParam ( r )
2024-07-30 10:44:02 -06:00
)
2025-04-09 14:35:43 -05:00
var req codersdk . CreateWorkspaceRequest
if ! httpapi . Read ( ctx , rw , r , & req ) {
return
}
var owner workspaceOwner
2025-05-08 14:41:17 -05:00
if mems . User != nil {
// This user fetch is an optimization path for the most common case of creating a
// workspace for 'Me'.
//
// This is also required to allow `owners` to create workspaces for users
// that are not in an organization.
2025-04-09 14:35:43 -05:00
owner = workspaceOwner {
2025-05-08 14:41:17 -05:00
ID : mems . User . ID ,
Username : mems . User . Username ,
AvatarURL : mems . User . AvatarURL ,
2025-04-09 14:35:43 -05:00
}
} else {
// A workspace can still be created if the caller can read the organization
// member. The organization is required, which can be sourced from the
// template.
//
// TODO: This code gets called twice for each workspace build request.
// This is inefficient and costs at most 2 extra RTTs to the DB.
// This can be optimized. It exists as it is now for code simplicity.
// The most common case is to create a workspace for 'Me'. Which does
// not enter this code branch.
template , ok := requestTemplate ( ctx , rw , req , api . Database )
if ! ok {
return
}
2025-05-08 14:41:17 -05:00
// If the caller can find the organization membership in the same org
// as the template, then they can continue.
orgIndex := slices . IndexFunc ( mems . Memberships , func ( mem httpmw . OrganizationMember ) bool {
return mem . OrganizationID == template . OrganizationID
})
if orgIndex == - 1 {
2025-04-09 14:35:43 -05:00
httpapi . ResourceNotFound ( rw )
return
}
2025-05-08 14:41:17 -05:00
member := mems . Memberships [ orgIndex ]
2025-04-09 14:35:43 -05:00
owner = workspaceOwner {
2025-05-08 14:41:17 -05:00
ID : member . UserID ,
Username : member . Username ,
AvatarURL : member . AvatarURL ,
2025-04-09 14:35:43 -05:00
}
}
2024-10-22 09:20:54 -05:00
aReq , commitAudit := audit . InitRequest [ database . WorkspaceTable ]( rw , & audit . RequestParams {
2024-07-30 10:44:02 -06:00
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionCreate ,
AdditionalFields : audit . AdditionalFields {
2025-04-09 14:35:43 -05:00
WorkspaceOwner : owner . Username ,
2024-07-30 10:44:02 -06:00
},
})
defer commitAudit ()
createWorkspace ( ctx , aReq , apiKey . UserID , api , owner , req , rw , r )
}
type workspaceOwner struct {
ID uuid . UUID
Username string
AvatarURL string
}
func createWorkspace (
ctx context . Context ,
2024-10-22 09:20:54 -05:00
auditReq * audit . Request [ database . WorkspaceTable ],
2024-07-30 10:44:02 -06:00
initiatorID uuid . UUID ,
api * API ,
owner workspaceOwner ,
req codersdk . CreateWorkspaceRequest ,
rw http . ResponseWriter ,
r * http . Request ,
) {
2025-04-09 14:35:43 -05:00
template , ok := requestTemplate ( ctx , rw , req , api . Database )
if ! ok {
2022-11-10 16:53:14 -06:00
return
}
2022-06-14 08:46:33 -05:00
2024-08-19 13:28:27 -05:00
// This is a premature auth check to avoid doing unnecessary work if the user
// doesn't have permission to create a workspace.
if ! api . Authorize ( r , policy . ActionCreate ,
rbac . ResourceWorkspace . InOrg ( template . OrganizationID ). WithOwner ( owner . ID . String ())) {
// If this check fails, return a proper unauthorized error to the user to indicate
// what is going on.
httpapi . Write ( ctx , rw , http . StatusForbidden , codersdk . Response {
Message : "Unauthorized to create workspace." ,
Detail : "You are unable to create a workspace in this organization. " +
"It is possible to have access to the template, but not be able to create a workspace. " +
"Please contact an administrator about your permissions if you feel this is an error." ,
Validations : nil ,
})
return
}
2024-07-30 10:44:02 -06:00
// Update audit log's organization
auditReq . UpdateOrganizationID ( template . OrganizationID )
// Do this upfront to save work. If this fails, the rest of the work
// would be wasted.
if ! api . Authorize ( r , policy . ActionCreate ,
rbac . ResourceWorkspace . InOrg ( template . OrganizationID ). WithOwner ( owner . ID . String ())) {
httpapi . ResourceNotFound ( rw )
return
}
2025-01-17 11:55:41 -06:00
// The user also needs permission to use the template. At this point they have
// read perms, but not necessarily "use". This is also checked in `db.InsertWorkspace`.
// Doing this up front can save some work below if the user doesn't have permission.
if ! api . Authorize ( r , policy . ActionUse , template ) {
httpapi . Write ( ctx , rw , http . StatusForbidden , codersdk . Response {
Message : fmt . Sprintf ( "Unauthorized access to use the template %q." , template . Name ),
Detail : "Although you are able to view the template, you are unable to create a workspace using it. " +
"Please contact an administrator about your permissions if you feel this is an error." ,
Validations : nil ,
})
return
}
2024-07-30 10:44:02 -06:00
2023-11-20 13:16:18 -06:00
templateAccessControl := ( * ( api . AccessControlStore . Load ())). GetTemplateAccessControl ( template )
if templateAccessControl . IsDeprecated () {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : fmt . Sprintf ( "Template %q has been deprecated, and cannot be used to create a new workspace." , template . Name ),
// Pass the deprecated message to the user.
Detail : templateAccessControl . Deprecated ,
Validations : nil ,
})
return
}
2024-07-30 10:44:02 -06:00
dbAutostartSchedule , err := validWorkspaceSchedule ( req . AutostartSchedule )
2022-05-30 20:19:17 +01:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Invalid Autostart Schedule." ,
2022-07-12 19:15:02 -05:00
Validations : [] codersdk . ValidationError {{ Field : "schedule" , Detail : err . Error ()}},
2022-05-30 20:19:17 +01:00
})
return
2022-05-23 23:31:41 +01:00
}
2023-07-20 06:35:41 -07:00
templateSchedule , err := ( * api . TemplateScheduleStore . Load ()). Get ( ctx , api . Database , template . ID )
2023-03-08 01:14:58 +11:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template schedule." ,
Detail : err . Error (),
})
return
}
2024-12-02 21:02:36 +00:00
nextStartAt := sql . NullTime {}
if dbAutostartSchedule . Valid {
next , err := schedule . NextAllowedAutostart ( dbtime . Now (), dbAutostartSchedule . String , templateSchedule )
if err == nil {
nextStartAt = sql . NullTime { Valid : true , Time : dbtime . Time ( next . UTC ())}
}
}
2024-07-30 10:44:02 -06:00
dbTTL , err := validWorkspaceTTLMillis ( req . TTLMillis , templateSchedule . DefaultTTL )
2022-06-07 13:37:45 +01:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-07-27 22:20:02 +01:00
Message : "Invalid Workspace Time to Shutdown." ,
2022-07-12 19:15:02 -05:00
Validations : [] codersdk . ValidationError {{ Field : "ttl_ms" , Detail : err . Error ()}},
2022-06-07 13:37:45 +01:00
})
return
}
2023-10-06 13:27:12 +04:00
// back-compatibility: default to "never" if not included.
dbAU := database . AutomaticUpdatesNever
2024-07-30 10:44:02 -06:00
if req . AutomaticUpdates != "" {
dbAU , err = validWorkspaceAutomaticUpdates ( req . AutomaticUpdates )
2023-10-06 13:27:12 +04:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Invalid Workspace Automatic Updates setting." ,
Validations : [] codersdk . ValidationError {{ Field : "automatic_updates" , Detail : err . Error ()}},
})
return
}
}
2023-02-14 08:27:06 -06:00
// TODO: This should be a system call as the actor might not be able to
// read other workspaces. Ideally we check the error on create and look for
// a postgres conflict error.
2022-09-21 17:07:00 -05:00
workspace , err := api . Database . GetWorkspaceByOwnerIDAndName ( ctx , database . GetWorkspaceByOwnerIDAndNameParams {
2024-07-30 10:44:02 -06:00
OwnerID : owner . ID ,
Name : req . Name ,
2022-05-16 14:36:27 -05:00
})
if err == nil {
// If the workspace already exists, don't allow creation.
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusConflict , codersdk . Response {
2024-07-30 10:44:02 -06:00
Message : fmt . Sprintf ( "Workspace %q already exists." , req . Name ),
2022-07-12 19:15:02 -05:00
Validations : [] codersdk . ValidationError {{
2022-05-16 14:36:27 -05:00
Field : "name" ,
2022-08-02 13:19:00 -04:00
Detail : "This value is already in use and should be unique." ,
2022-05-16 14:36:27 -05:00
}},
})
return
2024-12-02 20:54:32 +00:00
} else if ! errors . Is ( err , sql . ErrNoRows ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2024-07-30 10:44:02 -06:00
Message : fmt . Sprintf ( "Internal error fetching workspace by name %q." , req . Name ),
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2022-09-30 14:01:20 -04:00
var (
2024-12-11 13:38:13 +02:00
provisionerJob * database . ProvisionerJob
workspaceBuild * database . WorkspaceBuild
provisionerDaemons [] database . GetEligibleProvisionerDaemonsByProvisionerJobIDsRow
2022-09-30 14:01:20 -04:00
)
2025-04-24 09:39:38 -04:00
2022-03-07 11:40:54 -06:00
err = api . Database . InTx ( func ( db database . Store ) error {
2025-04-24 09:39:38 -04:00
var (
2025-05-14 14:15:36 +02:00
prebuildsClaimer = * api . PrebuildsClaimer . Load ()
2025-04-24 09:39:38 -04:00
workspaceID uuid . UUID
claimedWorkspace * database . Workspace
)
// If a template preset was chosen, try claim a prebuilt workspace.
if req . TemplateVersionPresetID != uuid . Nil {
// Try and claim an eligible prebuild, if available.
claimedWorkspace , err = claimPrebuild ( ctx , prebuildsClaimer , db , api . Logger , req , owner )
2025-04-28 16:37:41 -04:00
// If claiming fails with an expected error (no claimable prebuilds or AGPL does not support prebuilds),
// we fall back to creating a new workspace. Otherwise, propagate the unexpected error.
if err != nil {
isExpectedError := errors . Is ( err , prebuilds . ErrNoClaimablePrebuiltWorkspaces ) ||
errors . Is ( err , prebuilds . ErrAGPLDoesNotSupportPrebuiltWorkspaces )
fields := [] any {
slog . Error ( err ),
slog . F ( "workspace_name" , req . Name ),
slog . F ( "template_version_preset_id" , req . TemplateVersionPresetID ),
}
if ! isExpectedError {
// if it's an unexpected error - use error log level
api . Logger . Error ( ctx , "failed to claim prebuilt workspace" , fields ... )
return xerrors . Errorf ( "failed to claim prebuilt workspace: %w" , err )
}
// if it's an expected error - use warn log level
api . Logger . Warn ( ctx , "failed to claim prebuilt workspace" , fields ... )
// fall back to creating a new workspace
2025-04-24 09:39:38 -04:00
}
}
// No prebuild found; regular flow.
if claimedWorkspace == nil {
now := dbtime . Now ()
// Workspaces are created without any versions.
minimumWorkspace , err := db . InsertWorkspace ( ctx , database . InsertWorkspaceParams {
ID : uuid . New (),
CreatedAt : now ,
UpdatedAt : now ,
OwnerID : owner . ID ,
OrganizationID : template . OrganizationID ,
TemplateID : template . ID ,
Name : req . Name ,
AutostartSchedule : dbAutostartSchedule ,
NextStartAt : nextStartAt ,
Ttl : dbTTL ,
// The workspaces page will sort by last used at, and it's useful to
// have the newly created workspace at the top of the list!
LastUsedAt : dbtime . Now (),
AutomaticUpdates : dbAU ,
})
if err != nil {
return xerrors . Errorf ( "insert workspace: %w" , err )
}
workspaceID = minimumWorkspace . ID
} else {
// Prebuild found!
workspaceID = claimedWorkspace . ID
initiatorID = prebuildsClaimer . Initiator ()
2022-05-16 14:36:27 -05:00
}
2022-09-06 15:15:19 -03:00
2024-10-22 09:20:54 -05:00
// We have to refetch the workspace for the joined in fields.
// TODO: We can use WorkspaceTable for the builder to not require
// this extra fetch.
2025-04-24 09:39:38 -04:00
workspace , err = db . GetWorkspaceByID ( ctx , workspaceID )
2024-10-22 09:20:54 -05:00
if err != nil {
return xerrors . Errorf ( "get workspace by ID: %w" , err )
}
2025-07-22 13:39:26 +10:00
builder := wsbuilder . New ( workspace , database . WorkspaceTransitionStart , * api . BuildUsageChecker . Load ()).
2023-05-23 12:06:33 +04:00
Reason ( database . BuildReasonInitiator ).
2024-07-30 10:44:02 -06:00
Initiator ( initiatorID ).
2023-05-23 12:06:33 +04:00
ActiveVersion ().
2025-05-20 10:09:53 -05:00
Experiments ( api . Experiments ).
DeploymentValues ( api . DeploymentValues ).
2025-05-14 14:15:36 +02:00
RichParameterValues ( req . RichParameterValues )
2024-07-30 10:44:02 -06:00
if req . TemplateVersionID != uuid . Nil {
builder = builder . VersionID ( req . TemplateVersionID )
2023-08-31 15:07:58 -06:00
}
2025-04-24 09:39:38 -04:00
if req . TemplateVersionPresetID != uuid . Nil {
builder = builder . TemplateVersionPresetID ( req . TemplateVersionPresetID )
}
if claimedWorkspace != nil {
2025-05-12 16:19:03 +02:00
builder = builder . MarkPrebuiltWorkspaceClaim ()
2025-04-24 09:39:38 -04:00
}
2024-12-02 20:54:32 +00:00
workspaceBuild , provisionerJob , provisionerDaemons , err = builder . Build (
2023-09-19 10:25:57 +04:00
ctx ,
db ,
2025-06-23 12:35:15 -05:00
api . FileCache ,
2024-05-15 09:46:35 -05:00
func ( action policy . Action , object rbac . Objecter ) bool {
2023-05-23 12:06:33 +04:00
return api . Authorize ( r , action , object )
2023-10-18 15:08:02 -05:00
},
audit . WorkspaceBuildBaggageFromRequest ( r ),
)
2023-05-23 12:06:33 +04:00
return err
2022-11-14 11:57:33 -06:00
}, nil )
2022-01-25 13:52:58 -06:00
if err != nil {
2025-06-23 15:08:18 -05:00
httperror . WriteWorkspaceBuildError ( ctx , rw , err )
2022-03-07 11:40:54 -06:00
return
}
2025-06-23 15:08:18 -05:00
2023-09-19 10:25:57 +04:00
err = provisionerjobs . PostJob ( api . Pubsub , * provisionerJob )
if err != nil {
// Client probably doesn't care about this error, so just log it.
api . Logger . Error ( ctx , "failed to post provisioner job to pubsub" , slog . Error ( err ))
}
2024-12-02 20:54:32 +00:00
2025-01-15 17:43:11 +00:00
// nolint:gocritic // Need system context to fetch admins
admins , err := findTemplateAdmins ( dbauthz . AsSystemRestricted ( ctx ), api . Database )
if err != nil {
api . Logger . Error ( ctx , "find template admins" , slog . Error ( err ))
} else {
for _ , admin := range admins {
// Don't send notifications to user which initiated the event.
if admin . ID == initiatorID {
continue
}
api . notifyWorkspaceCreated ( ctx , admin . ID , workspace , req . RichParameterValues )
}
}
2024-10-22 09:20:54 -05:00
auditReq . New = workspace . WorkspaceTable ()
2022-09-10 11:07:45 -05:00
2022-06-17 00:26:40 -05:00
api . Telemetry . Report ( & telemetry . Snapshot {
Workspaces : [] telemetry . Workspace { telemetry . ConvertWorkspace ( workspace )},
2023-05-23 12:06:33 +04:00
WorkspaceBuilds : [] telemetry . WorkspaceBuild { telemetry . ConvertWorkspaceBuild ( * workspaceBuild )},
2022-06-17 00:26:40 -05:00
})
2022-09-16 14:54:23 -04:00
apiBuild , err := api . convertWorkspaceBuild (
2023-05-23 12:06:33 +04:00
* workspaceBuild ,
2022-09-16 14:54:23 -04:00
workspace ,
2023-06-20 15:07:18 -05:00
database . GetProvisionerJobsByIDsWithQueuePositionRow {
ProvisionerJob : * provisionerJob ,
QueuePosition : 0 ,
},
2022-09-16 14:54:23 -04:00
[] database . WorkspaceResource {},
[] database . WorkspaceResourceMetadatum {},
[] database . WorkspaceAgent {},
[] database . WorkspaceApp {},
2025-03-31 10:55:44 -04:00
[] database . WorkspaceAppStatus {},
2023-09-25 16:47:17 -05:00
[] database . WorkspaceAgentScript {},
[] database . WorkspaceAgentLogSource {},
2022-11-28 16:53:56 -03:00
database . TemplateVersion {},
2024-12-11 13:38:13 +02:00
provisionerDaemons ,
2022-09-16 14:54:23 -04:00
)
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-09-16 14:54:23 -04:00
Message : "Internal error converting workspace build." ,
Detail : err . Error (),
})
return
}
2024-01-24 14:13:14 +00:00
w , err := convertWorkspace (
2024-07-30 10:44:02 -06:00
initiatorID ,
2022-09-16 14:54:23 -04:00
workspace ,
apiBuild ,
template ,
2023-12-15 13:38:47 -05:00
api . Options . AllowWorkspaceRenames ,
2025-03-31 10:55:44 -04:00
codersdk . WorkspaceAppStatus {},
2024-01-24 14:13:14 +00:00
)
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error converting workspace." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusCreated , w )
2022-02-05 18:24:51 -06:00
}
2025-04-09 14:35:43 -05:00
func requestTemplate ( ctx context . Context , rw http . ResponseWriter , req codersdk . CreateWorkspaceRequest , db database . Store ) ( database . Template , bool ) {
// If we were given a `TemplateVersionID`, we need to determine the `TemplateID` from it.
templateID := req . TemplateID
if templateID == uuid . Nil {
templateVersion , err := db . GetTemplateVersionByID ( ctx , req . TemplateVersionID )
if httpapi . Is404Error ( err ) {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : fmt . Sprintf ( "Template version %q doesn't exist." , req . TemplateVersionID ),
Validations : [] codersdk . ValidationError {{
Field : "template_version_id" ,
Detail : "template not found" ,
}},
})
return database . Template {}, false
}
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template version." ,
Detail : err . Error (),
})
return database . Template {}, false
}
if templateVersion . Archived {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Archived template versions cannot be used to make a workspace." ,
Validations : [] codersdk . ValidationError {
{
Field : "template_version_id" ,
Detail : "template version archived" ,
},
},
})
return database . Template {}, false
}
templateID = templateVersion . TemplateID . UUID
}
template , err := db . GetTemplateByID ( ctx , templateID )
if httpapi . Is404Error ( err ) {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : fmt . Sprintf ( "Template %q doesn't exist." , templateID ),
Validations : [] codersdk . ValidationError {{
Field : "template_id" ,
Detail : "template not found" ,
}},
})
return database . Template {}, false
}
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template." ,
Detail : err . Error (),
})
return database . Template {}, false
}
if template . Deleted {
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : fmt . Sprintf ( "Template %q has been deleted!" , template . Name ),
})
return database . Template {}, false
}
return template , true
}
2025-04-24 09:39:38 -04:00
func claimPrebuild ( ctx context . Context , claimer prebuilds . Claimer , db database . Store , logger slog . Logger , req codersdk . CreateWorkspaceRequest , owner workspaceOwner ) ( * database . Workspace , error ) {
claimedID , err := claimer . Claim ( ctx , owner . ID , req . Name , req . TemplateVersionPresetID )
if err != nil {
// TODO: enhance this by clarifying whether this *specific* prebuild failed or whether there are none to claim.
return nil , xerrors . Errorf ( "claim prebuild: %w" , err )
}
lookup , err := db . GetWorkspaceByID ( ctx , * claimedID )
if err != nil {
logger . Error ( ctx , "unable to find claimed workspace by ID" , slog . Error ( err ), slog . F ( "claimed_prebuild_id" , claimedID . String ()))
return nil , xerrors . Errorf ( "find claimed workspace by ID %q: %w" , claimedID . String (), err )
}
return & lookup , nil
}
2024-12-20 13:53:10 +00:00
func ( api * API ) notifyWorkspaceCreated (
ctx context . Context ,
2025-01-15 17:43:11 +00:00
receiverID uuid . UUID ,
2024-12-20 13:53:10 +00:00
workspace database . Workspace ,
parameters [] codersdk . WorkspaceBuildParameter ,
) {
log := api . Logger . With ( slog . F ( "workspace_id" , workspace . ID ))
template , err := api . Database . GetTemplateByID ( ctx , workspace . TemplateID )
if err != nil {
log . Warn ( ctx , "failed to fetch template for workspace creation notification" , slog . F ( "template_id" , workspace . TemplateID ), slog . Error ( err ))
return
}
owner , err := api . Database . GetUserByID ( ctx , workspace . OwnerID )
if err != nil {
log . Warn ( ctx , "failed to fetch user for workspace creation notification" , slog . F ( "owner_id" , workspace . OwnerID ), slog . Error ( err ))
return
}
version , err := api . Database . GetTemplateVersionByID ( ctx , template . ActiveVersionID )
if err != nil {
log . Warn ( ctx , "failed to fetch template version for workspace creation notification" , slog . F ( "template_version_id" , template . ActiveVersionID ), slog . Error ( err ))
return
}
buildParameters := make ([] map [ string ] any , len ( parameters ))
for idx , parameter := range parameters {
buildParameters [ idx ] = map [ string ] any {
"name" : parameter . Name ,
"value" : parameter . Value ,
}
}
if _ , err := api . NotificationsEnqueuer . EnqueueWithData (
// nolint:gocritic // Need notifier actor to enqueue notifications
dbauthz . AsNotifier ( ctx ),
2025-01-15 17:43:11 +00:00
receiverID ,
2024-12-20 13:53:10 +00:00
notifications . TemplateWorkspaceCreated ,
map [ string ] string {
2025-03-25 11:29:02 +01:00
"workspace" : workspace . Name ,
"template" : template . Name ,
"version" : version . Name ,
"workspace_owner_username" : owner . Username ,
2024-12-20 13:53:10 +00:00
},
map [ string ] any {
"workspace" : map [ string ] any { "id" : workspace . ID , "name" : workspace . Name },
"template" : map [ string ] any { "id" : template . ID , "name" : template . Name },
"template_version" : map [ string ] any { "id" : version . ID , "name" : version . Name },
2025-01-30 17:44:04 +00:00
"owner" : map [ string ] any { "id" : owner . ID , "name" : owner . Name , "email" : owner . Email },
2024-12-20 13:53:10 +00:00
"parameters" : buildParameters ,
},
"api-workspaces-create" ,
// Associate this notification with all the related entities
workspace . ID , workspace . OwnerID , workspace . TemplateID , workspace . OrganizationID ,
); err != nil {
log . Warn ( ctx , "failed to notify of workspace creation" , slog . Error ( err ))
}
}
2022-12-19 18:43:46 +01:00
// @Summary Update workspace metadata by ID
// @ID update-workspace-metadata-by-id
// @Security CoderSessionToken
2022-12-21 15:37:30 +01:00
// @Accept json
2022-12-19 18:43:46 +01:00
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Param request body codersdk.UpdateWorkspaceRequest true "Metadata update request"
// @Success 204
// @Router /workspaces/{workspace} [patch]
2022-08-26 12:28:38 +03:00
func ( api * API ) patchWorkspace ( rw http . ResponseWriter , r * http . Request ) {
2022-09-10 11:07:45 -05:00
var (
2022-09-21 17:07:00 -05:00
ctx = r . Context ()
2022-09-10 11:07:45 -05:00
workspace = httpmw . WorkspaceParam ( r )
2022-09-19 23:11:01 -05:00
auditor = api . Auditor . Load ()
2024-10-22 09:20:54 -05:00
aReq , commitAudit = audit . InitRequest [ database . WorkspaceTable ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : workspace . OrganizationID ,
2022-09-10 11:07:45 -05:00
})
)
defer commitAudit ()
2024-10-22 09:20:54 -05:00
aReq . Old = workspace . WorkspaceTable ()
2022-09-10 11:07:45 -05:00
2022-08-26 12:28:38 +03:00
var req codersdk . UpdateWorkspaceRequest
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-08-26 12:28:38 +03:00
return
}
if req . Name == "" || req . Name == workspace . Name {
2024-10-22 09:20:54 -05:00
aReq . New = workspace . WorkspaceTable ()
2022-08-26 12:28:38 +03:00
// Nothing changed, optionally this could be an error.
rw . WriteHeader ( http . StatusNoContent )
return
}
2022-09-10 11:07:45 -05:00
2022-08-26 12:28:38 +03:00
// The reason we double check here is in case more fields can be
// patched in the future, it's enough if one changes.
name := workspace . Name
if req . Name != "" || req . Name != workspace . Name {
2023-12-15 13:38:47 -05:00
if ! api . Options . AllowWorkspaceRenames {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Workspace renames are not allowed." ,
})
return
}
2022-08-26 12:28:38 +03:00
name = req . Name
}
2022-09-21 17:07:00 -05:00
newWorkspace , err := api . Database . UpdateWorkspace ( ctx , database . UpdateWorkspaceParams {
2022-08-26 12:28:38 +03:00
ID : workspace . ID ,
Name : name ,
})
if err != nil {
// The query protects against updating deleted workspaces and
// the existence of the workspace is checked in the request,
// if we get ErrNoRows it means the workspace was deleted.
//
// We could do this check earlier but we'd need to start a
// transaction.
if errors . Is ( err , sql . ErrNoRows ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusMethodNotAllowed , codersdk . Response {
2022-08-26 12:28:38 +03:00
Message : fmt . Sprintf ( "Workspace %q is deleted and cannot be updated." , workspace . Name ),
})
return
}
// Check if the name was already in use.
2022-08-29 17:00:52 -05:00
if database . IsUniqueViolation ( err ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusConflict , codersdk . Response {
2022-08-26 12:28:38 +03:00
Message : fmt . Sprintf ( "Workspace %q already exists." , req . Name ),
Validations : [] codersdk . ValidationError {{
Field : "name" ,
Detail : "This value is already in use and should be unique." ,
}},
})
return
}
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-08-26 12:28:38 +03:00
Message : "Internal error updating workspace." ,
Detail : err . Error (),
})
return
}
2024-11-01 14:17:05 +11:00
api . publishWorkspaceUpdate ( ctx , workspace . OwnerID , wspubsub . WorkspaceEvent {
Kind : wspubsub . WorkspaceEventKindMetadataUpdate ,
WorkspaceID : workspace . ID ,
})
2022-09-10 11:07:45 -05:00
aReq . New = newWorkspace
2024-10-22 09:20:54 -05:00
2022-08-26 12:28:38 +03:00
rw . WriteHeader ( http . StatusNoContent )
}
2022-12-19 18:43:46 +01:00
// @Summary Update workspace autostart schedule by ID
// @ID update-workspace-autostart-schedule-by-id
// @Security CoderSessionToken
2022-12-21 15:37:30 +01:00
// @Accept json
2022-12-19 18:43:46 +01:00
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Param request body codersdk.UpdateWorkspaceAutostartRequest true "Schedule update request"
// @Success 204
// @Router /workspaces/{workspace}/autostart [put]
2022-05-25 22:14:08 -05:00
func ( api * API ) putWorkspaceAutostart ( rw http . ResponseWriter , r * http . Request ) {
2022-09-10 11:07:45 -05:00
var (
2022-09-21 17:07:00 -05:00
ctx = r . Context ()
2022-09-10 11:07:45 -05:00
workspace = httpmw . WorkspaceParam ( r )
2022-09-19 23:11:01 -05:00
auditor = api . Auditor . Load ()
2024-10-22 09:20:54 -05:00
aReq , commitAudit = audit . InitRequest [ database . WorkspaceTable ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : workspace . OrganizationID ,
2022-09-10 11:07:45 -05:00
})
)
defer commitAudit ()
2024-10-22 09:20:54 -05:00
aReq . Old = workspace . WorkspaceTable ()
2022-09-10 11:07:45 -05:00
2022-04-07 10:03:35 +01:00
var req codersdk . UpdateWorkspaceAutostartRequest
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-04-07 10:03:35 +01:00
return
}
2022-11-09 14:36:25 -05:00
dbSched , err := validWorkspaceSchedule ( req . Schedule )
2022-06-07 13:37:45 +01:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Invalid autostart schedule." ,
2022-07-12 19:15:02 -05:00
Validations : [] codersdk . ValidationError {{ Field : "schedule" , Detail : err . Error ()}},
2022-06-02 11:23:34 +01:00
})
return
2022-04-07 10:03:35 +01:00
}
2023-04-04 22:48:35 +10:00
// Check if the template allows users to configure autostart.
2023-07-20 06:35:41 -07:00
templateSchedule , err := ( * api . TemplateScheduleStore . Load ()). Get ( ctx , api . Database , workspace . TemplateID )
2023-04-04 22:48:35 +10:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error getting template schedule options." ,
Detail : err . Error (),
})
return
}
if ! templateSchedule . UserAutostartEnabled {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Autostart is not allowed for workspaces using this template." ,
Validations : [] codersdk . ValidationError {{ Field : "schedule" , Detail : "Autostart is not allowed for workspaces using this template." }},
})
return
}
2024-12-02 21:02:36 +00:00
nextStartAt := sql . NullTime {}
if dbSched . Valid {
next , err := schedule . NextAllowedAutostart ( dbtime . Now (), dbSched . String , templateSchedule )
if err == nil {
nextStartAt = sql . NullTime { Valid : true , Time : dbtime . Time ( next . UTC ())}
}
}
2022-09-21 17:07:00 -05:00
err = api . Database . UpdateWorkspaceAutostart ( ctx , database . UpdateWorkspaceAutostartParams {
2022-04-07 10:03:35 +01:00
ID : workspace . ID ,
AutostartSchedule : dbSched ,
2024-12-02 21:02:36 +00:00
NextStartAt : nextStartAt ,
2022-04-07 10:03:35 +01:00
})
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error updating workspace autostart schedule." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-04-07 10:03:35 +01:00
})
return
}
2022-09-10 11:07:45 -05:00
newWorkspace := workspace
newWorkspace . AutostartSchedule = dbSched
2024-10-22 09:20:54 -05:00
aReq . New = newWorkspace . WorkspaceTable ()
2022-09-10 11:07:45 -05:00
rw . WriteHeader ( http . StatusNoContent )
2022-04-07 10:03:35 +01:00
}
2022-12-19 18:43:46 +01:00
// @Summary Update workspace TTL by ID
// @ID update-workspace-ttl-by-id
// @Security CoderSessionToken
2022-12-21 15:37:30 +01:00
// @Accept json
2022-12-19 18:43:46 +01:00
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Param request body codersdk.UpdateWorkspaceTTLRequest true "Workspace TTL update request"
// @Success 204
// @Router /workspaces/{workspace}/ttl [put]
2022-05-25 22:14:08 -05:00
func ( api * API ) putWorkspaceTTL ( rw http . ResponseWriter , r * http . Request ) {
2022-09-10 11:07:45 -05:00
var (
2022-09-21 17:07:00 -05:00
ctx = r . Context ()
2022-09-10 11:07:45 -05:00
workspace = httpmw . WorkspaceParam ( r )
2022-09-19 23:11:01 -05:00
auditor = api . Auditor . Load ()
2024-10-22 09:20:54 -05:00
aReq , commitAudit = audit . InitRequest [ database . WorkspaceTable ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : workspace . OrganizationID ,
2022-09-10 11:07:45 -05:00
})
)
defer commitAudit ()
2024-10-22 09:20:54 -05:00
aReq . Old = workspace . WorkspaceTable ()
2022-09-10 11:07:45 -05:00
2022-05-19 20:09:27 +01:00
var req codersdk . UpdateWorkspaceTTLRequest
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-04-07 10:03:35 +01:00
return
}
2022-09-10 11:07:45 -05:00
var dbTTL sql . NullInt64
2022-06-14 17:09:24 +01:00
err := api . Database . InTx ( func ( s database . Store ) error {
2023-07-20 06:35:41 -07:00
templateSchedule , err := ( * api . TemplateScheduleStore . Load ()). Get ( ctx , s , workspace . TemplateID )
2023-03-08 01:14:58 +11:00
if err != nil {
return xerrors . Errorf ( "get template schedule: %w" , err )
}
2023-04-04 22:48:35 +10:00
if ! templateSchedule . UserAutostopEnabled {
return codersdk . ValidationError { Field : "ttl_ms" , Detail : "Custom autostop TTL is not allowed for workspaces using this template." }
}
2023-03-08 01:14:58 +11:00
// don't override 0 ttl with template default here because it indicates
2023-04-04 22:48:35 +10:00
// disabled autostop
2022-12-05 17:19:30 -05:00
var validityErr error
2024-03-20 10:37:57 -05:00
dbTTL , validityErr = validWorkspaceTTLMillis ( req . TTLMillis , 0 )
2022-12-05 17:19:30 -05:00
if validityErr != nil {
return codersdk . ValidationError { Field : "ttl_ms" , Detail : validityErr . Error ()}
2022-06-14 17:09:24 +01:00
}
2022-09-21 17:07:00 -05:00
if err := s . UpdateWorkspaceTTL ( ctx , database . UpdateWorkspaceTTLParams {
2022-06-09 22:10:24 +01:00
ID : workspace . ID ,
Ttl : dbTTL ,
}); err != nil {
2022-07-27 22:20:02 +01:00
return xerrors . Errorf ( "update workspace time until shutdown: %w" , err )
2022-06-09 22:10:24 +01:00
}
2025-01-13 21:37:57 +00:00
// If autostop has been disabled, we want to remove the deadline from the
// existing workspace build (if there is one).
if ! dbTTL . Valid {
build , err := s . GetLatestWorkspaceBuildByWorkspaceID ( ctx , workspace . ID )
if err != nil {
return xerrors . Errorf ( "get latest workspace build: %w" , err )
}
if build . Transition == database . WorkspaceTransitionStart {
if err = s . UpdateWorkspaceBuildDeadlineByID ( ctx , database . UpdateWorkspaceBuildDeadlineByIDParams {
2025-08-07 11:00:31 +10:00
ID : build . ID ,
// Use the max_deadline as the new build deadline. It will
// either be zero (our target), or a non-zero value that we
// need to abide by anyway due to template policy.
//
// Previously, we would always set the deadline to zero,
// which was incorrect behavior. When max_deadline is
// non-zero, deadline must be set to a non-zero value that
// is less than max_deadline.
//
// Disabling TTL autostop (at a workspace or template level)
// does not trump the template's autostop requirement.
//
// Refer to the comments on schedule.CalculateAutostop for
// more information.
Deadline : build . MaxDeadline ,
2025-01-13 21:37:57 +00:00
MaxDeadline : build . MaxDeadline ,
UpdatedAt : dbtime . Time ( api . Clock . Now ()),
}); err != nil {
return xerrors . Errorf ( "update workspace build deadline: %w" , err )
}
}
}
2022-06-09 22:10:24 +01:00
return nil
2022-11-14 11:57:33 -06:00
}, nil )
2022-04-07 10:03:35 +01:00
if err != nil {
2022-07-27 22:20:02 +01:00
resp := codersdk . Response {
Message : "Error updating workspace time until shutdown." ,
2022-06-14 17:09:24 +01:00
}
2022-07-27 22:20:02 +01:00
var validErr codersdk . ValidationError
if errors . As ( err , & validErr ) {
resp . Validations = [] codersdk . ValidationError { validErr }
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , resp )
2022-07-27 22:20:02 +01:00
return
}
resp . Detail = err . Error ()
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , resp )
2022-04-07 10:03:35 +01:00
return
}
2022-06-09 22:10:24 +01:00
2022-09-10 11:07:45 -05:00
newWorkspace := workspace
newWorkspace . Ttl = dbTTL
2024-10-22 09:20:54 -05:00
aReq . New = newWorkspace . WorkspaceTable ()
2022-09-10 11:07:45 -05:00
rw . WriteHeader ( http . StatusNoContent )
2022-04-07 10:03:35 +01:00
}
2023-08-24 13:25:54 -05:00
// @Summary Update workspace dormancy status by id.
// @ID update-workspace-dormancy-status-by-id
2023-06-28 16:12:49 -05:00
// @Security CoderSessionToken
// @Accept json
// @Produce json
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
2023-08-24 13:25:54 -05:00
// @Param request body codersdk.UpdateWorkspaceDormancy true "Make a workspace dormant or active"
2023-08-03 19:46:02 -05:00
// @Success 200 {object} codersdk.Workspace
2023-08-24 13:25:54 -05:00
// @Router /workspaces/{workspace}/dormant [put]
func ( api * API ) putWorkspaceDormant ( rw http . ResponseWriter , r * http . Request ) {
2023-10-05 13:41:07 -05:00
var (
ctx = r . Context ()
2024-10-22 09:20:54 -05:00
oldWorkspace = httpmw . WorkspaceParam ( r )
2024-01-24 13:39:19 +00:00
apiKey = httpmw . APIKey ( r )
2023-10-05 13:41:07 -05:00
auditor = api . Auditor . Load ()
2024-10-22 09:20:54 -05:00
aReq , commitAudit = audit . InitRequest [ database . WorkspaceTable ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
2024-10-22 09:20:54 -05:00
OrganizationID : oldWorkspace . OrganizationID ,
2023-10-05 13:41:07 -05:00
})
)
2024-10-22 09:20:54 -05:00
aReq . Old = oldWorkspace . WorkspaceTable ()
2023-10-05 13:41:07 -05:00
defer commitAudit ()
2023-06-28 16:12:49 -05:00
2023-08-24 13:25:54 -05:00
var req codersdk . UpdateWorkspaceDormancy
2023-06-28 16:12:49 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
return
}
// If the workspace is already in the desired state do nothing!
2024-10-22 09:20:54 -05:00
if oldWorkspace . DormantAt . Valid == req . Dormant {
2024-07-11 13:38:33 -06:00
rw . WriteHeader ( http . StatusNotModified )
2023-06-28 16:12:49 -05:00
return
}
2023-08-24 13:25:54 -05:00
dormantAt := sql . NullTime {
Valid : req . Dormant ,
2023-06-28 16:12:49 -05:00
}
2023-08-24 13:25:54 -05:00
if req . Dormant {
2023-09-01 19:50:12 +03:00
dormantAt . Time = dbtime . Now ()
2023-06-28 16:12:49 -05:00
}
2024-10-22 09:20:54 -05:00
newWorkspace , err := api . Database . UpdateWorkspaceDormantDeletingAt ( ctx , database . UpdateWorkspaceDormantDeletingAtParams {
ID : oldWorkspace . ID ,
2023-08-24 13:25:54 -05:00
DormantAt : dormantAt ,
2023-06-28 16:12:49 -05:00
})
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error updating workspace locked status." ,
Detail : err . Error (),
})
return
}
2024-07-24 13:38:21 -03:00
// We don't need to notify the owner if they are the one making the request.
2024-10-22 09:20:54 -05:00
if req . Dormant && apiKey . UserID != newWorkspace . OwnerID {
2024-07-29 11:20:04 -03:00
initiator , initiatorErr := api . Database . GetUserByID ( ctx , apiKey . UserID )
if initiatorErr != nil {
2024-07-24 13:38:21 -03:00
api . Logger . Warn (
ctx ,
2024-07-29 11:20:04 -03:00
"failed to fetch the user that marked the workspace as dormant" ,
2024-07-24 13:38:21 -03:00
slog . Error ( err ),
2024-10-22 09:20:54 -05:00
slog . F ( "workspace_id" , newWorkspace . ID ),
2024-07-24 13:38:21 -03:00
slog . F ( "user_id" , apiKey . UserID ),
)
2024-07-29 11:20:04 -03:00
}
2024-10-22 09:20:54 -05:00
tmpl , tmplErr := api . Database . GetTemplateByID ( ctx , newWorkspace . TemplateID )
2024-07-29 11:20:04 -03:00
if tmplErr != nil {
api . Logger . Warn (
2024-07-24 13:38:21 -03:00
ctx ,
2024-07-29 11:20:04 -03:00
"failed to fetch the template of the workspace marked as dormant" ,
slog . Error ( err ),
2024-10-22 09:20:54 -05:00
slog . F ( "workspace_id" , newWorkspace . ID ),
slog . F ( "template_id" , newWorkspace . TemplateID ),
2024-07-29 11:20:04 -03:00
)
}
if initiatorErr == nil && tmplErr == nil {
2024-08-19 15:49:47 -03:00
dormantTime := dbtime . Now (). Add ( time . Duration ( tmpl . TimeTilDormant ))
2024-07-29 11:20:04 -03:00
_ , err = api . NotificationsEnqueuer . Enqueue (
2024-11-12 12:40:46 +00:00
// nolint:gocritic // Need notifier actor to enqueue notifications
dbauthz . AsNotifier ( ctx ),
2024-10-22 09:20:54 -05:00
newWorkspace . OwnerID ,
2024-07-29 11:20:04 -03:00
notifications . TemplateWorkspaceDormant ,
map [ string ] string {
2024-10-22 09:20:54 -05:00
"name" : newWorkspace . Name ,
2024-07-29 11:20:04 -03:00
"reason" : "a " + initiator . Username + " request" ,
2024-08-19 15:49:47 -03:00
"timeTilDormant" : humanize . Time ( dormantTime ),
2024-07-24 13:38:21 -03:00
},
2024-07-29 11:20:04 -03:00
"api" ,
2024-10-22 09:20:54 -05:00
newWorkspace . ID ,
newWorkspace . OwnerID ,
newWorkspace . TemplateID ,
newWorkspace . OrganizationID ,
2024-07-24 13:38:21 -03:00
)
if err != nil {
api . Logger . Warn ( ctx , "failed to notify of workspace marked as dormant" , slog . Error ( err ))
}
}
}
2024-10-22 09:20:54 -05:00
// We have to refetch the workspace to get the joined in fields.
workspace , err := api . Database . GetWorkspaceByID ( ctx , newWorkspace . ID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching workspace." ,
Detail : err . Error (),
})
return
}
2023-08-03 19:46:02 -05:00
data , err := api . workspaceData ( ctx , [] database . Workspace { workspace })
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching workspace resources." ,
Detail : err . Error (),
})
return
}
2024-10-22 09:20:54 -05:00
// TODO: This is a strange error since it occurs after the mutatation.
// An example of why we should join in fields to prevent this forbidden error
// from being sent, when the action did succeed.
2023-08-17 13:22:03 -05:00
if len ( data . templates ) == 0 {
httpapi . Forbidden ( rw )
return
}
2024-10-22 09:20:54 -05:00
aReq . New = newWorkspace
2024-01-24 14:13:14 +00:00
2025-03-31 10:55:44 -04:00
appStatus := codersdk . WorkspaceAppStatus {}
if len ( data . appStatuses ) > 0 {
appStatus = data . appStatuses [ 0 ]
}
2024-01-24 14:13:14 +00:00
w , err := convertWorkspace (
2024-01-24 13:39:19 +00:00
apiKey . UserID ,
2023-08-03 19:46:02 -05:00
workspace ,
data . builds [ 0 ],
data . templates [ 0 ],
2023-12-15 13:38:47 -05:00
api . Options . AllowWorkspaceRenames ,
2025-03-31 10:55:44 -04:00
appStatus ,
2024-01-24 14:13:14 +00:00
)
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error converting workspace." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusOK , w )
2023-06-28 16:12:49 -05:00
}
2022-12-19 18:43:46 +01:00
// @Summary Extend workspace deadline by ID
// @ID extend-workspace-deadline-by-id
// @Security CoderSessionToken
2022-12-21 15:37:30 +01:00
// @Accept json
2022-12-19 18:43:46 +01:00
// @Produce json
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Param request body codersdk.PutExtendWorkspaceRequest true "Extend deadline update request"
// @Success 200 {object} codersdk.Response
// @Router /workspaces/{workspace}/extend [put]
2022-05-26 18:08:11 +01:00
func ( api * API ) putExtendWorkspace ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-05-26 18:08:11 +01:00
workspace := httpmw . WorkspaceParam ( r )
var req codersdk . PutExtendWorkspaceRequest
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-05-26 18:08:11 +01:00
return
}
2022-05-30 20:19:17 +01:00
code := http . StatusOK
2022-07-12 19:15:02 -05:00
resp := codersdk . Response {}
2022-05-26 18:08:11 +01:00
err := api . Database . InTx ( func ( s database . Store ) error {
2022-09-21 17:07:00 -05:00
build , err := s . GetLatestWorkspaceBuildByWorkspaceID ( ctx , workspace . ID )
2022-05-26 18:08:11 +01:00
if err != nil {
code = http . StatusInternalServerError
2022-06-14 22:39:15 +01:00
resp . Message = "Error fetching workspace build."
2022-05-26 18:08:11 +01:00
return xerrors . Errorf ( "get latest workspace build: %w" , err )
}
2022-09-21 17:07:00 -05:00
job , err := s . GetProvisionerJobByID ( ctx , build . JobID )
2022-06-14 22:39:15 +01:00
if err != nil {
code = http . StatusInternalServerError
resp . Message = "Error fetching workspace provisioner job."
return xerrors . Errorf ( "get provisioner job: %w" , err )
}
2022-05-26 18:08:11 +01:00
if build . Transition != database . WorkspaceTransitionStart {
code = http . StatusConflict
2022-06-07 09:33:06 -05:00
resp . Message = "Workspace must be started, current status: " + string ( build . Transition )
2022-05-26 18:08:11 +01:00
return xerrors . Errorf ( "workspace must be started, current status: %s" , build . Transition )
}
2022-06-14 22:39:15 +01:00
if ! job . CompletedAt . Valid {
code = http . StatusConflict
resp . Message = "Workspace is still building!"
return xerrors . Errorf ( "workspace is still building" )
}
if build . Deadline . IsZero () {
code = http . StatusConflict
resp . Message = "Workspace shutdown is manual."
return xerrors . Errorf ( "workspace shutdown is manual" )
}
2022-05-27 20:04:33 +01:00
newDeadline := req . Deadline . UTC ()
2022-11-09 14:36:25 -05:00
if err := validWorkspaceDeadline ( job . CompletedAt . Time , newDeadline ); err != nil {
2022-07-29 15:01:17 +01:00
// NOTE(Cian): Putting the error in the Message field on request from the FE folks.
// Normally, we would put the validation error in Validations, but this endpoint is
// not tied to a form or specific named user input on the FE.
2022-05-26 18:08:11 +01:00
code = http . StatusBadRequest
2022-07-29 15:01:17 +01:00
resp . Message = "Cannot extend workspace: " + err . Error ()
2022-05-30 20:19:17 +01:00
return err
2022-05-26 18:08:11 +01:00
}
2023-03-08 01:14:58 +11:00
if ! build . MaxDeadline . IsZero () && newDeadline . After ( build . MaxDeadline ) {
code = http . StatusBadRequest
resp . Message = "Cannot extend workspace beyond max deadline."
return xerrors . New ( "Cannot extend workspace: deadline is beyond max deadline imposed by template" )
}
2022-05-26 18:08:11 +01:00
2023-09-22 16:22:07 +01:00
if err := s . UpdateWorkspaceBuildDeadlineByID ( ctx , database . UpdateWorkspaceBuildDeadlineByIDParams {
ID : build . ID ,
UpdatedAt : dbtime . Now (),
Deadline : newDeadline ,
MaxDeadline : build . MaxDeadline ,
2022-05-26 18:08:11 +01:00
}); err != nil {
2022-05-30 20:19:17 +01:00
code = http . StatusInternalServerError
2022-06-07 09:33:06 -05:00
resp . Message = "Failed to extend workspace deadline."
2022-05-26 18:08:11 +01:00
return xerrors . Errorf ( "update workspace build: %w" , err )
}
2022-06-07 09:33:06 -05:00
resp . Message = "Deadline updated to " + newDeadline . Format ( time . RFC3339 ) + "."
2022-05-26 18:08:11 +01:00
return nil
2022-11-14 11:57:33 -06:00
}, nil )
2022-05-26 18:08:11 +01:00
if err != nil {
2022-09-21 17:07:00 -05:00
api . Logger . Info ( ctx , "extending workspace" , slog . Error ( err ))
2022-05-26 18:08:11 +01:00
}
2024-11-01 14:17:05 +11:00
api . publishWorkspaceUpdate ( ctx , workspace . OwnerID , wspubsub . WorkspaceEvent {
Kind : wspubsub . WorkspaceEventKindMetadataUpdate ,
WorkspaceID : workspace . ID ,
})
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , code , resp )
2022-05-26 18:08:11 +01:00
}
2024-03-20 16:44:12 +00:00
// @Summary Post Workspace Usage by ID
// @ID post-workspace-usage-by-id
// @Security CoderSessionToken
// @Tags Workspaces
2024-06-14 10:08:45 -04:00
// @Accept json
2024-03-20 16:44:12 +00:00
// @Param workspace path string true "Workspace ID" format(uuid)
2024-06-14 10:08:45 -04:00
// @Param request body codersdk.PostWorkspaceUsageRequest false "Post workspace usage request"
2024-03-20 16:44:12 +00:00
// @Success 204
// @Router /workspaces/{workspace}/usage [post]
func ( api * API ) postWorkspaceUsage ( rw http . ResponseWriter , r * http . Request ) {
workspace := httpmw . WorkspaceParam ( r )
2024-05-15 09:46:35 -05:00
if ! api . Authorize ( r , policy . ActionUpdate , workspace ) {
2024-03-20 16:44:12 +00:00
httpapi . Forbidden ( rw )
return
}
2024-06-10 15:35:23 -04:00
api . statsReporter . TrackUsage ( workspace . ID )
2024-06-14 10:08:45 -04:00
if ! api . Experiments . Enabled ( codersdk . ExperimentWorkspaceUsage ) {
// Continue previous behavior if the experiment is not enabled.
rw . WriteHeader ( http . StatusNoContent )
return
}
if r . Body == http . NoBody {
// Continue previous behavior if no body is present.
rw . WriteHeader ( http . StatusNoContent )
return
}
ctx := r . Context ()
var req codersdk . PostWorkspaceUsageRequest
if ! httpapi . Read ( ctx , rw , r , & req ) {
return
}
if req . AgentID == uuid . Nil && req . AppName == "" {
// Continue previous behavior if body is empty.
rw . WriteHeader ( http . StatusNoContent )
return
}
if req . AgentID == uuid . Nil {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Invalid request" ,
Validations : [] codersdk . ValidationError {{
Field : "agent_id" ,
Detail : "must be set when app_name is set" ,
}},
})
return
}
if req . AppName == "" {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Invalid request" ,
Validations : [] codersdk . ValidationError {{
Field : "app_name" ,
Detail : "must be set when agent_id is set" ,
}},
})
return
}
if ! slices . Contains ( codersdk . AllowedAppNames , req . AppName ) {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Invalid request" ,
Validations : [] codersdk . ValidationError {{
Field : "app_name" ,
Detail : fmt . Sprintf ( "must be one of %v" , codersdk . AllowedAppNames ),
}},
})
return
}
stat := & proto . Stats {
ConnectionCount : 1 ,
}
switch req . AppName {
case codersdk . UsageAppNameVscode :
stat . SessionCountVscode = 1
case codersdk . UsageAppNameJetbrains :
stat . SessionCountJetbrains = 1
case codersdk . UsageAppNameReconnectingPty :
stat . SessionCountReconnectingPty = 1
case codersdk . UsageAppNameSSH :
stat . SessionCountSsh = 1
default :
// This means the app_name is in the codersdk.AllowedAppNames but not being
// handled by this switch statement.
httpapi . InternalServerError ( rw , xerrors . Errorf ( "unknown app_name %q" , req . AppName ))
return
}
agent , err := api . Database . GetWorkspaceAgentByID ( ctx , req . AgentID )
if err != nil {
if httpapi . Is404Error ( err ) {
httpapi . ResourceNotFound ( rw )
return
}
httpapi . InternalServerError ( rw , err )
return
}
template , err := api . Database . GetTemplateByID ( ctx , workspace . TemplateID )
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
2024-09-19 11:52:14 -04:00
err = api . statsReporter . ReportAgentStats ( ctx , dbtime . Now (), workspace , agent , template . Name , stat , true )
2024-06-14 10:08:45 -04:00
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
2024-03-20 16:44:12 +00:00
rw . WriteHeader ( http . StatusNoContent )
}
2024-01-24 13:39:19 +00:00
// @Summary Favorite workspace by ID.
// @ID favorite-workspace-by-id
// @Security CoderSessionToken
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Success 204
// @Router /workspaces/{workspace}/favorite [put]
func ( api * API ) putFavoriteWorkspace ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
workspace = httpmw . WorkspaceParam ( r )
apiKey = httpmw . APIKey ( r )
auditor = api . Auditor . Load ()
)
if apiKey . UserID != workspace . OwnerID {
httpapi . Write ( ctx , rw , http . StatusForbidden , codersdk . Response {
Message : "You can only favorite workspaces that you own." ,
})
return
}
2024-10-22 09:20:54 -05:00
aReq , commitAudit := audit . InitRequest [ database . WorkspaceTable ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : workspace . OrganizationID ,
2024-01-24 13:39:19 +00:00
})
defer commitAudit ()
2024-10-22 09:20:54 -05:00
aReq . Old = workspace . WorkspaceTable ()
2024-01-24 13:39:19 +00:00
err := api . Database . FavoriteWorkspace ( ctx , workspace . ID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error setting workspace as favorite" ,
Detail : err . Error (),
})
return
}
2024-10-22 09:20:54 -05:00
aReq . New = workspace . WorkspaceTable ()
2024-01-24 13:39:19 +00:00
aReq . New . Favorite = true
rw . WriteHeader ( http . StatusNoContent )
}
// @Summary Unfavorite workspace by ID.
// @ID unfavorite-workspace-by-id
// @Security CoderSessionToken
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Success 204
// @Router /workspaces/{workspace}/favorite [delete]
func ( api * API ) deleteFavoriteWorkspace ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
workspace = httpmw . WorkspaceParam ( r )
apiKey = httpmw . APIKey ( r )
auditor = api . Auditor . Load ()
)
if apiKey . UserID != workspace . OwnerID {
httpapi . Write ( ctx , rw , http . StatusForbidden , codersdk . Response {
Message : "You can only un-favorite workspaces that you own." ,
})
return
}
2024-10-22 09:20:54 -05:00
aReq , commitAudit := audit . InitRequest [ database . WorkspaceTable ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : workspace . OrganizationID ,
2024-01-24 13:39:19 +00:00
})
defer commitAudit ()
2024-10-22 09:20:54 -05:00
aReq . Old = workspace . WorkspaceTable ()
2024-01-24 13:39:19 +00:00
err := api . Database . UnfavoriteWorkspace ( ctx , workspace . ID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error unsetting workspace as favorite" ,
Detail : err . Error (),
})
return
}
2024-10-22 09:20:54 -05:00
aReq . New = workspace . WorkspaceTable ()
2024-01-24 13:39:19 +00:00
aReq . New . Favorite = false
rw . WriteHeader ( http . StatusNoContent )
}
2023-10-06 13:27:12 +04:00
// @Summary Update workspace automatic updates by ID
// @ID update-workspace-automatic-updates-by-id
// @Security CoderSessionToken
// @Accept json
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Param request body codersdk.UpdateWorkspaceAutomaticUpdatesRequest true "Automatic updates request"
// @Success 204
// @Router /workspaces/{workspace}/autoupdates [put]
func ( api * API ) putWorkspaceAutoupdates ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
workspace = httpmw . WorkspaceParam ( r )
auditor = api . Auditor . Load ()
2024-10-22 09:20:54 -05:00
aReq , commitAudit = audit . InitRequest [ database . WorkspaceTable ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : workspace . OrganizationID ,
2023-10-06 13:27:12 +04:00
})
)
defer commitAudit ()
2024-10-22 09:20:54 -05:00
aReq . Old = workspace . WorkspaceTable ()
2023-10-06 13:27:12 +04:00
var req codersdk . UpdateWorkspaceAutomaticUpdatesRequest
if ! httpapi . Read ( ctx , rw , r , & req ) {
return
}
if ! database . AutomaticUpdates ( req . AutomaticUpdates ). Valid () {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Invalid request" ,
Validations : [] codersdk . ValidationError {{ Field : "automatic_updates" , Detail : "must be always or never" }},
})
return
}
err := api . Database . UpdateWorkspaceAutomaticUpdates ( ctx , database . UpdateWorkspaceAutomaticUpdatesParams {
ID : workspace . ID ,
AutomaticUpdates : database . AutomaticUpdates ( req . AutomaticUpdates ),
})
if httpapi . Is404Error ( err ) {
httpapi . ResourceNotFound ( rw )
return
}
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error updating workspace automatic updates setting" ,
Detail : err . Error (),
})
return
}
newWorkspace := workspace
newWorkspace . AutomaticUpdates = database . AutomaticUpdates ( req . AutomaticUpdates )
2024-10-22 09:20:54 -05:00
aReq . New = newWorkspace . WorkspaceTable ()
2023-10-06 13:27:12 +04:00
rw . WriteHeader ( http . StatusNoContent )
}
2023-11-08 23:24:56 -06:00
// @Summary Resolve workspace autostart by id.
// @ID resolve-workspace-autostart-by-id
// @Security CoderSessionToken
// @Produce json
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Success 200 {object} codersdk.ResolveAutostartResponse
// @Router /workspaces/{workspace}/resolve-autostart [get]
func ( api * API ) resolveAutostart ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
workspace = httpmw . WorkspaceParam ( r )
)
template , err := api . Database . GetTemplateByID ( ctx , workspace . TemplateID )
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
templateAccessControl := ( * ( api . AccessControlStore . Load ())). GetTemplateAccessControl ( template )
useActiveVersion := templateAccessControl . RequireActiveVersion || workspace . AutomaticUpdates == database . AutomaticUpdatesAlways
if ! useActiveVersion {
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . ResolveAutostartResponse {})
return
}
build , err := api . Database . GetLatestWorkspaceBuildByWorkspaceID ( ctx , workspace . ID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching latest workspace build." ,
Detail : err . Error (),
})
return
}
if build . TemplateVersionID == template . ActiveVersionID {
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . ResolveAutostartResponse {})
return
}
version , err := api . Database . GetTemplateVersionByID ( ctx , template . ActiveVersionID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template version." ,
Detail : err . Error (),
})
return
}
dbVersionParams , err := api . Database . GetTemplateVersionParameters ( ctx , version . ID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template version parameters." ,
Detail : err . Error (),
})
return
}
dbBuildParams , err := api . Database . GetWorkspaceBuildParameters ( ctx , build . ID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching latest workspace build parameters." ,
Detail : err . Error (),
})
return
}
versionParams , err := db2sdk . TemplateVersionParameters ( dbVersionParams )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error converting template version parameters." ,
Detail : err . Error (),
})
return
}
resolver := codersdk . ParameterResolver {
Rich : db2sdk . WorkspaceBuildParameters ( dbBuildParams ),
}
var response codersdk . ResolveAutostartResponse
for _ , param := range versionParams {
_ , err := resolver . ValidateResolve ( param , nil )
// There's a parameter mismatch if we get an error back from the
// resolver.
response . ParameterMismatch = err != nil
if response . ParameterMismatch {
break
}
}
httpapi . Write ( ctx , rw , http . StatusOK , response )
}
2022-12-19 18:43:46 +01:00
// @Summary Watch workspace by ID
2023-01-13 12:27:21 +01:00
// @ID watch-workspace-by-id
2022-12-19 18:43:46 +01:00
// @Security CoderSessionToken
// @Produce text/event-stream
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Success 200 {object} codersdk.Response
// @Router /workspaces/{workspace}/watch [get]
2025-03-28 17:13:20 -04:00
// @Deprecated Use /workspaces/{workspace}/watch-ws instead
func ( api * API ) watchWorkspaceSSE ( rw http . ResponseWriter , r * http . Request ) {
api . watchWorkspace ( rw , r , httpapi . ServerSentEventSender )
}
// @Summary Watch workspace by ID via WebSockets
// @ID watch-workspace-by-id-via-websockets
// @Security CoderSessionToken
// @Produce json
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Success 200 {object} codersdk.ServerSentEvent
// @Router /workspaces/{workspace}/watch-ws [get]
func ( api * API ) watchWorkspaceWS ( rw http . ResponseWriter , r * http . Request ) {
api . watchWorkspace ( rw , r , httpapi . OneWayWebSocketEventSender )
}
func ( api * API ) watchWorkspace (
rw http . ResponseWriter ,
r * http . Request ,
connect httpapi . EventSender ,
) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-05-18 16:16:26 -05:00
workspace := httpmw . WorkspaceParam ( r )
2024-01-24 13:39:19 +00:00
apiKey := httpmw . APIKey ( r )
2022-05-18 16:16:26 -05:00
2025-03-28 17:13:20 -04:00
sendEvent , senderClosed , err := connect ( rw , r )
2022-05-18 16:16:26 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-09-16 14:54:23 -04:00
Message : "Internal error setting up server-sent events." ,
Detail : err . Error (),
})
2022-05-18 16:16:26 -05:00
return
}
2022-11-01 16:57:38 +02:00
// Prevent handler from returning until the sender is closed.
defer func () {
<- senderClosed
}()
2022-05-18 16:16:26 -05:00
2024-02-14 17:14:49 +00:00
sendUpdate := func ( _ context . Context , _ [] byte ) {
2022-11-07 07:25:18 -08:00
workspace , err := api . Database . GetWorkspaceByID ( ctx , workspace . ID )
if err != nil {
2025-03-28 17:13:20 -04:00
_ = sendEvent ( codersdk . ServerSentEvent {
2022-11-07 07:25:18 -08:00
Type : codersdk . ServerSentEventTypeError ,
Data : codersdk . Response {
Message : "Internal error fetching workspace." ,
Detail : err . Error (),
},
})
return
}
data , err := api . workspaceData ( ctx , [] database . Workspace { workspace })
if err != nil {
2025-03-28 17:13:20 -04:00
_ = sendEvent ( codersdk . ServerSentEvent {
2022-11-07 07:25:18 -08:00
Type : codersdk . ServerSentEventTypeError ,
Data : codersdk . Response {
Message : "Internal error fetching workspace data." ,
Detail : err . Error (),
},
})
return
}
2023-08-17 13:22:03 -05:00
if len ( data . templates ) == 0 {
2025-03-28 17:13:20 -04:00
_ = sendEvent ( codersdk . ServerSentEvent {
2023-08-17 13:22:03 -05:00
Type : codersdk . ServerSentEventTypeError ,
Data : codersdk . Response {
Message : "Forbidden reading template of selected workspace." ,
},
})
return
}
2022-11-07 07:25:18 -08:00
2025-03-31 10:55:44 -04:00
appStatus := codersdk . WorkspaceAppStatus {}
if len ( data . appStatuses ) > 0 {
appStatus = data . appStatuses [ 0 ]
}
2024-01-24 14:13:14 +00:00
w , err := convertWorkspace (
apiKey . UserID ,
workspace ,
data . builds [ 0 ],
data . templates [ 0 ],
api . Options . AllowWorkspaceRenames ,
2025-03-31 10:55:44 -04:00
appStatus ,
2024-01-24 14:13:14 +00:00
)
if err != nil {
2025-03-28 17:13:20 -04:00
_ = sendEvent ( codersdk . ServerSentEvent {
2024-01-24 14:13:14 +00:00
Type : codersdk . ServerSentEventTypeError ,
Data : codersdk . Response {
Message : "Internal error converting workspace." ,
Detail : err . Error (),
},
})
}
2025-03-28 17:13:20 -04:00
_ = sendEvent ( codersdk . ServerSentEvent {
2022-11-07 07:25:18 -08:00
Type : codersdk . ServerSentEventTypeData ,
2024-01-24 14:13:14 +00:00
Data : w ,
2022-11-07 07:25:18 -08:00
})
2022-11-09 11:01:34 -06:00
}
2024-11-01 14:17:05 +11:00
cancelWorkspaceSubscribe , err := api . Pubsub . SubscribeWithErr ( wspubsub . WorkspaceEventChannel ( workspace . OwnerID ),
wspubsub . HandleWorkspaceEvent (
func ( ctx context . Context , payload wspubsub . WorkspaceEvent , err error ) {
if err != nil {
return
}
if payload . WorkspaceID != workspace . ID {
return
}
sendUpdate ( ctx , nil )
}))
2022-11-07 07:25:18 -08:00
if err != nil {
2025-03-28 17:13:20 -04:00
_ = sendEvent ( codersdk . ServerSentEvent {
2022-11-07 07:25:18 -08:00
Type : codersdk . ServerSentEventTypeError ,
Data : codersdk . Response {
Message : "Internal error subscribing to workspace events." ,
Detail : err . Error (),
},
})
return
}
2022-11-09 11:01:34 -06:00
defer cancelWorkspaceSubscribe ()
// This is required to show whether the workspace is up-to-date.
cancelTemplateSubscribe , err := api . Pubsub . Subscribe ( watchTemplateChannel ( workspace . TemplateID ), sendUpdate )
if err != nil {
2025-03-28 17:13:20 -04:00
_ = sendEvent ( codersdk . ServerSentEvent {
2022-11-09 11:01:34 -06:00
Type : codersdk . ServerSentEventTypeError ,
Data : codersdk . Response {
Message : "Internal error subscribing to template events." ,
Detail : err . Error (),
},
})
return
}
defer cancelTemplateSubscribe ()
2022-11-07 07:25:18 -08:00
// An initial ping signals to the request that the server is now ready
// and the client can begin servicing a channel with data.
2025-03-28 17:13:20 -04:00
_ = sendEvent ( codersdk . ServerSentEvent {
2022-11-07 07:25:18 -08:00
Type : codersdk . ServerSentEventTypePing ,
})
2023-08-28 15:14:17 -03:00
// Send updated workspace info after connection is established. This avoids
// missing updates if the client connects after an update.
sendUpdate ( ctx , nil )
2022-11-07 07:25:18 -08:00
2022-05-18 16:16:26 -05:00
for {
select {
2022-09-21 17:07:00 -05:00
case <- ctx . Done ():
2022-09-16 14:54:23 -04:00
return
2022-11-01 16:57:38 +02:00
case <- senderClosed :
return
2022-05-18 16:16:26 -05:00
}
}
}
2024-09-16 16:31:05 -03:00
// @Summary Get workspace timings by ID
// @ID get-workspace-timings-by-id
// @Security CoderSessionToken
// @Produce json
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
2024-10-14 09:31:03 -03:00
// @Success 200 {object} codersdk.WorkspaceBuildTimings
2024-09-16 16:31:05 -03:00
// @Router /workspaces/{workspace}/timings [get]
func ( api * API ) workspaceTimings ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
workspace = httpmw . WorkspaceParam ( r )
)
build , err := api . Database . GetLatestWorkspaceBuildByWorkspaceID ( ctx , workspace . ID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching workspace build." ,
Detail : err . Error (),
})
return
}
2024-10-14 09:31:03 -03:00
timings , err := api . buildTimings ( ctx , build )
if err != nil {
2024-09-16 16:31:05 -03:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2024-10-14 09:31:03 -03:00
Message : "Internal error fetching timings." ,
2024-09-16 16:31:05 -03:00
Detail : err . Error (),
})
return
}
2024-10-14 09:31:03 -03:00
httpapi . Write ( ctx , rw , http . StatusOK , timings )
2024-09-16 16:31:05 -03:00
}
2025-07-31 09:05:09 -06:00
// @Summary Update workspace ACL
// @ID update-workspace-acl
// @Security CoderSessionToken
// @Accept json
// @Produce json
// @Tags Workspaces
// @Param workspace path string true "Workspace ID" format(uuid)
// @Param request body codersdk.UpdateWorkspaceACL true "Update workspace ACL request"
// @Success 204
// @Router /workspaces/{workspace}/acl [patch]
func ( api * API ) patchWorkspaceACL ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
workspace = httpmw . WorkspaceParam ( r )
auditor = api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . WorkspaceTable ]( rw , & audit . RequestParams {
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : workspace . OrganizationID ,
})
)
defer commitAudit ()
aReq . Old = workspace . WorkspaceTable ()
var req codersdk . UpdateWorkspaceACL
if ! httpapi . Read ( ctx , rw , r , & req ) {
return
}
2025-08-07 10:14:58 -06:00
validErrs := acl . Validate ( ctx , api . Database , WorkspaceACLUpdateValidator ( req ))
2025-07-31 09:05:09 -06:00
if len ( validErrs ) > 0 {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2025-08-07 10:14:58 -06:00
Message : "Invalid request to update workspace ACL" ,
2025-07-31 09:05:09 -06:00
Validations : validErrs ,
})
return
}
err := api . Database . InTx ( func ( tx database . Store ) error {
var err error
workspace , err = tx . GetWorkspaceByID ( ctx , workspace . ID )
if err != nil {
return xerrors . Errorf ( "get template by ID: %w" , err )
}
for id , role := range req . UserRoles {
if role == codersdk . WorkspaceRoleDeleted {
delete ( workspace . UserACL , id )
continue
}
workspace . UserACL [ id ] = database . WorkspaceACLEntry {
Permissions : db2sdk . WorkspaceRoleActions ( role ),
}
}
for id , role := range req . GroupRoles {
if role == codersdk . WorkspaceRoleDeleted {
delete ( workspace . GroupACL , id )
continue
}
workspace . GroupACL [ id ] = database . WorkspaceACLEntry {
Permissions : db2sdk . WorkspaceRoleActions ( role ),
}
}
err = tx . UpdateWorkspaceACLByID ( ctx , database . UpdateWorkspaceACLByIDParams {
ID : workspace . ID ,
UserACL : workspace . UserACL ,
GroupACL : workspace . GroupACL ,
})
if err != nil {
return xerrors . Errorf ( "update workspace ACL by ID: %w" , err )
}
workspace , err = tx . GetWorkspaceByID ( ctx , workspace . ID )
if err != nil {
return xerrors . Errorf ( "get updated workspace by ID: %w" , err )
}
return nil
}, nil )
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
aReq . New = workspace . WorkspaceTable ()
rw . WriteHeader ( http . StatusNoContent )
}
2022-09-16 14:54:23 -04:00
type workspaceData struct {
2023-12-15 13:38:47 -05:00
templates [] database . Template
builds [] codersdk . WorkspaceBuild
2025-03-31 10:55:44 -04:00
appStatuses [] codersdk . WorkspaceAppStatus
2023-12-15 13:38:47 -05:00
allowRenames bool
2022-09-16 14:54:23 -04:00
}
2023-08-17 13:22:03 -05:00
// workspacesData only returns the data the caller can access. If the caller
// does not have the correct perms to read a given template, the template will
// not be returned.
// So the caller must check the templates & users exist before using them.
2022-09-16 14:54:23 -04:00
func ( api * API ) workspaceData ( ctx context . Context , workspaces [] database . Workspace ) ( workspaceData , error ) {
2022-04-25 16:11:03 -05:00
workspaceIDs := make ([] uuid . UUID , 0 , len ( workspaces ))
templateIDs := make ([] uuid . UUID , 0 , len ( workspaces ))
for _ , workspace := range workspaces {
workspaceIDs = append ( workspaceIDs , workspace . ID )
templateIDs = append ( templateIDs , workspace . TemplateID )
2022-06-08 20:23:35 -05:00
}
2025-03-31 10:55:44 -04:00
var (
templates [] database . Template
builds [] database . WorkspaceBuild
appStatuses [] database . WorkspaceAppStatus
eg errgroup . Group
)
eg . Go ( func () ( err error ) {
templates , err = api . Database . GetTemplatesWithFilter ( ctx , database . GetTemplatesWithFilterParams {
IDs : templateIDs ,
})
if err != nil && ! errors . Is ( err , sql . ErrNoRows ) {
return xerrors . Errorf ( "get templates: %w" , err )
}
return nil
2022-06-14 08:46:33 -05:00
})
2025-03-31 10:55:44 -04:00
eg . Go ( func () ( err error ) {
// This query must be run as system restricted to be efficient.
// nolint:gocritic
builds , err = api . Database . GetLatestWorkspaceBuildsByWorkspaceIDs ( dbauthz . AsSystemRestricted ( ctx ), workspaceIDs )
if err != nil && ! errors . Is ( err , sql . ErrNoRows ) {
return xerrors . Errorf ( "get workspace builds: %w" , err )
}
return nil
})
eg . Go ( func () ( err error ) {
// This query must be run as system restricted to be efficient.
// nolint:gocritic
appStatuses , err = api . Database . GetLatestWorkspaceAppStatusesByWorkspaceIDs ( dbauthz . AsSystemRestricted ( ctx ), workspaceIDs )
if err != nil && ! errors . Is ( err , sql . ErrNoRows ) {
return xerrors . Errorf ( "get workspace app statuses: %w" , err )
}
return nil
})
err := eg . Wait ()
if err != nil {
return workspaceData {}, err
2022-09-16 14:54:23 -04:00
}
2024-10-22 09:20:54 -05:00
data , err := api . workspaceBuildsData ( ctx , builds )
2022-09-16 14:54:23 -04:00
if err != nil {
return workspaceData {}, xerrors . Errorf ( "get workspace builds data: %w" , err )
}
apiBuilds , err := api . convertWorkspaceBuilds (
builds ,
workspaces ,
data . jobs ,
data . resources ,
data . metadata ,
data . agents ,
data . apps ,
2025-03-31 10:55:44 -04:00
data . appStatuses ,
2023-09-25 16:47:17 -05:00
data . scripts ,
data . logSources ,
2022-11-28 16:53:56 -03:00
data . templateVersions ,
2024-12-11 13:38:13 +02:00
data . provisionerDaemons ,
2022-09-16 14:54:23 -04:00
)
if err != nil {
return workspaceData {}, xerrors . Errorf ( "convert workspace builds: %w" , err )
}
return workspaceData {
2023-12-15 13:38:47 -05:00
templates : templates ,
2025-03-31 10:55:44 -04:00
appStatuses : db2sdk . WorkspaceAppStatuses ( appStatuses ),
2023-12-15 13:38:47 -05:00
builds : apiBuilds ,
allowRenames : api . Options . AllowWorkspaceRenames ,
2022-09-16 14:54:23 -04:00
}, nil
}
2024-01-24 13:39:19 +00:00
func convertWorkspaces ( requesterID uuid . UUID , workspaces [] database . Workspace , data workspaceData ) ([] codersdk . Workspace , error ) {
2022-09-16 14:54:23 -04:00
buildByWorkspaceID := map [ uuid . UUID ] codersdk . WorkspaceBuild {}
for _ , workspaceBuild := range data . builds {
buildByWorkspaceID [ workspaceBuild . WorkspaceID ] = workspaceBuild
2022-04-25 16:11:03 -05:00
}
templateByID := map [ uuid . UUID ] database . Template {}
2022-09-16 14:54:23 -04:00
for _ , template := range data . templates {
2022-04-25 16:11:03 -05:00
templateByID [ template . ID ] = template
}
2025-03-31 10:55:44 -04:00
appStatusesByWorkspaceID := map [ uuid . UUID ] codersdk . WorkspaceAppStatus {}
for _ , appStatus := range data . appStatuses {
appStatusesByWorkspaceID [ appStatus . WorkspaceID ] = appStatus
}
2022-09-16 14:54:23 -04:00
2022-04-25 16:11:03 -05:00
apiWorkspaces := make ([] codersdk . Workspace , 0 , len ( workspaces ))
for _ , workspace := range workspaces {
2023-08-17 13:22:03 -05:00
// If any data is missing from the workspace, just skip returning
// this workspace. This is not ideal, but the user cannot read
// all the workspace's data, so do not show them.
// Ideally we could just return some sort of "unknown" for the missing
// fields?
2022-04-25 16:11:03 -05:00
build , exists := buildByWorkspaceID [ workspace . ID ]
if ! exists {
2023-08-17 13:22:03 -05:00
continue
2022-04-25 16:11:03 -05:00
}
template , exists := templateByID [ workspace . TemplateID ]
if ! exists {
2023-08-17 13:22:03 -05:00
continue
2022-04-25 16:11:03 -05:00
}
2025-03-31 10:55:44 -04:00
appStatus := appStatusesByWorkspaceID [ workspace . ID ]
2022-09-16 14:54:23 -04:00
2024-01-24 14:13:14 +00:00
w , err := convertWorkspace (
2024-01-24 13:39:19 +00:00
requesterID ,
2022-09-16 14:54:23 -04:00
workspace ,
build ,
template ,
2023-12-15 13:38:47 -05:00
data . allowRenames ,
2025-03-31 10:55:44 -04:00
appStatus ,
2024-01-24 14:13:14 +00:00
)
if err != nil {
return nil , xerrors . Errorf ( "convert workspace: %w" , err )
}
apiWorkspaces = append ( apiWorkspaces , w )
2022-04-25 16:11:03 -05:00
}
2023-05-22 17:51:29 -03:00
return apiWorkspaces , nil
}
2022-06-01 16:49:43 -07:00
func convertWorkspace (
2024-01-24 13:39:19 +00:00
requesterID uuid . UUID ,
2022-06-01 16:49:43 -07:00
workspace database . Workspace ,
2022-09-16 14:54:23 -04:00
workspaceBuild codersdk . WorkspaceBuild ,
2022-06-01 16:49:43 -07:00
template database . Template ,
2023-12-15 13:38:47 -05:00
allowRenames bool ,
2025-03-31 10:55:44 -04:00
latestAppStatus codersdk . WorkspaceAppStatus ,
2024-01-24 14:13:14 +00:00
) ( codersdk . Workspace , error ) {
if requesterID == uuid . Nil {
return codersdk . Workspace {}, xerrors . Errorf ( "developer error: requesterID cannot be uuid.Nil!" )
}
2022-06-02 11:23:34 +01:00
var autostartSchedule * string
if workspace . AutostartSchedule . Valid {
autostartSchedule = & workspace . AutostartSchedule . String
}
2023-08-24 13:25:54 -05:00
var dormantAt * time . Time
if workspace . DormantAt . Valid {
dormantAt = & workspace . DormantAt . Time
2023-06-28 16:12:49 -05:00
}
2023-08-24 13:25:54 -05:00
var deletingAt * time . Time
2023-07-20 22:01:11 -05:00
if workspace . DeletingAt . Valid {
2023-08-24 13:25:54 -05:00
deletingAt = & workspace . DeletingAt . Time
2023-07-20 22:01:11 -05:00
}
2024-12-02 21:02:36 +00:00
var nextStartAt * time . Time
if workspace . NextStartAt . Valid {
nextStartAt = & workspace . NextStartAt . Time
}
2023-07-10 12:40:11 +03:00
failingAgents := [] uuid . UUID {}
for _ , resource := range workspaceBuild . Resources {
for _ , agent := range resource . Agents {
if ! agent . Health . Healthy {
failingAgents = append ( failingAgents , agent . ID )
}
}
}
2023-07-20 22:01:11 -05:00
ttlMillis := convertWorkspaceTTLMillis ( workspace . Ttl )
2024-04-11 13:08:51 -06:00
// If the template doesn't allow a workspace-configured value, then report the
// template value instead.
if ! template . AllowUserAutostop {
ttlMillis = convertWorkspaceTTLMillis ( sql . NullInt64 { Valid : true , Int64 : template . DefaultTTL })
}
2023-06-28 16:12:49 -05:00
2024-01-24 13:39:19 +00:00
// Only show favorite status if you own the workspace.
requesterFavorite := workspace . OwnerID == requesterID && workspace . Favorite
2025-03-31 10:55:44 -04:00
appStatus := & latestAppStatus
if latestAppStatus . ID == uuid . Nil {
appStatus = nil
}
2025-07-15 14:11:04 +01:00
2022-03-22 13:17:50 -06:00
return codersdk . Workspace {
2022-11-21 11:43:53 +01:00
ID : workspace . ID ,
CreatedAt : workspace . CreatedAt ,
UpdatedAt : workspace . UpdatedAt ,
OwnerID : workspace . OwnerID ,
2025-05-29 13:12:13 -03:00
OwnerName : workspace . OwnerUsername ,
2024-10-22 09:20:54 -05:00
OwnerAvatarURL : workspace . OwnerAvatarUrl ,
2023-03-21 09:10:22 -05:00
OrganizationID : workspace . OrganizationID ,
2024-10-22 09:20:54 -05:00
OrganizationName : workspace . OrganizationName ,
2022-11-21 11:43:53 +01:00
TemplateID : workspace . TemplateID ,
LatestBuild : workspaceBuild ,
2025-03-31 10:55:44 -04:00
LatestAppStatus : appStatus ,
2024-10-22 09:20:54 -05:00
TemplateName : workspace . TemplateName ,
TemplateIcon : workspace . TemplateIcon ,
TemplateDisplayName : workspace . TemplateDisplayName ,
2022-11-21 11:43:53 +01:00
TemplateAllowUserCancelWorkspaceJobs : template . AllowUserCancelWorkspaceJobs ,
2023-08-27 11:26:20 -05:00
TemplateActiveVersionID : template . ActiveVersionID ,
2023-10-19 18:21:52 -05:00
TemplateRequireActiveVersion : template . RequireActiveVersion ,
2025-05-19 16:59:15 -05:00
TemplateUseClassicParameterFlow : template . UseClassicParameterFlow ,
2022-11-21 11:43:53 +01:00
Outdated : workspaceBuild . TemplateVersionID . String () != template . ActiveVersionID . String (),
Name : workspace . Name ,
AutostartSchedule : autostartSchedule ,
TTLMillis : ttlMillis ,
LastUsedAt : workspace . LastUsedAt ,
2023-08-24 13:25:54 -05:00
DeletingAt : deletingAt ,
DormantAt : dormantAt ,
2023-07-10 12:40:11 +03:00
Health : codersdk . WorkspaceHealth {
Healthy : len ( failingAgents ) == 0 ,
FailingAgents : failingAgents ,
},
2023-10-06 13:27:12 +04:00
AutomaticUpdates : codersdk . AutomaticUpdates ( workspace . AutomaticUpdates ),
2023-12-15 13:38:47 -05:00
AllowRenames : allowRenames ,
2024-01-24 13:39:19 +00:00
Favorite : requesterFavorite ,
2024-12-02 21:02:36 +00:00
NextStartAt : nextStartAt ,
2025-07-15 14:11:04 +01:00
IsPrebuild : workspace . IsPrebuild (),
2024-01-24 14:13:14 +00:00
}, nil
2022-01-25 13:52:58 -06:00
}
2022-05-19 20:09:27 +01:00
2022-06-02 11:23:34 +01:00
func convertWorkspaceTTLMillis ( i sql . NullInt64 ) * int64 {
2022-05-19 20:09:27 +01:00
if ! i . Valid {
return nil
}
2022-06-02 11:23:34 +01:00
millis := time . Duration ( i . Int64 ). Milliseconds ()
return & millis
2022-05-19 20:09:27 +01:00
}
2022-05-27 20:04:33 +01:00
2024-03-20 10:37:57 -05:00
func validWorkspaceTTLMillis ( millis * int64 , templateDefault time . Duration ) ( sql . NullInt64 , error ) {
2022-06-02 11:23:34 +01:00
if ptr . NilOrZero ( millis ) {
2023-03-08 01:14:58 +11:00
if templateDefault == 0 {
2022-11-09 14:36:25 -05:00
return sql . NullInt64 {}, nil
}
return sql . NullInt64 {
2023-03-08 01:14:58 +11:00
Int64 : int64 ( templateDefault ),
2022-11-09 14:36:25 -05:00
Valid : true ,
}, nil
2022-05-27 20:04:33 +01:00
}
2022-06-02 11:23:34 +01:00
dur := time . Duration ( * millis ) * time . Millisecond
truncated := dur . Truncate ( time . Minute )
2025-08-07 11:00:31 +10:00
if truncated < ttlMinimum {
2022-07-29 15:01:17 +01:00
return sql . NullInt64 {}, errTTLMin
2022-05-30 20:19:17 +01:00
}
2025-08-07 11:00:31 +10:00
if truncated > ttlMaximum {
2022-07-29 15:01:17 +01:00
return sql . NullInt64 {}, errTTLMax
2022-05-30 20:19:17 +01:00
}
return sql . NullInt64 {
Valid : true ,
Int64 : int64 ( truncated ),
}, nil
}
2023-10-06 13:27:12 +04:00
func validWorkspaceAutomaticUpdates ( updates codersdk . AutomaticUpdates ) ( database . AutomaticUpdates , error ) {
if updates == "" {
return database . AutomaticUpdatesNever , nil
}
dbAU := database . AutomaticUpdates ( updates )
if ! dbAU . Valid () {
return "" , xerrors . New ( "Automatic updates must be always or never" )
}
return dbAU , nil
}
2022-11-09 14:36:25 -05:00
func validWorkspaceDeadline ( startedAt , newDeadline time . Time ) error {
2022-06-14 22:39:15 +01:00
soon := time . Now (). Add ( 29 * time . Minute )
if newDeadline . Before ( soon ) {
2022-07-29 15:01:17 +01:00
return errDeadlineTooSoon
2022-05-30 20:19:17 +01:00
}
2022-06-14 22:39:15 +01:00
// No idea how this could happen.
if newDeadline . Before ( startedAt ) {
2022-07-29 15:01:17 +01:00
return errDeadlineBeforeStart
2022-05-30 20:19:17 +01:00
}
return nil
2022-05-27 20:04:33 +01:00
}
2022-06-02 11:23:34 +01:00
2022-11-09 14:36:25 -05:00
func validWorkspaceSchedule ( s * string ) ( sql . NullString , error ) {
2022-06-02 11:23:34 +01:00
if ptr . NilOrEmpty ( s ) {
return sql . NullString {}, nil
}
2023-09-04 16:48:25 +03:00
_ , err := cron . Weekly ( * s )
2022-06-02 11:23:34 +01:00
if err != nil {
return sql . NullString {}, err
}
return sql . NullString {
Valid : true ,
String : * s ,
}, nil
}
2022-06-14 08:46:33 -05:00
2024-11-01 14:17:05 +11:00
func ( api * API ) publishWorkspaceUpdate ( ctx context . Context , ownerID uuid . UUID , event wspubsub . WorkspaceEvent ) {
err := event . Validate ()
if err != nil {
api . Logger . Warn ( ctx , "invalid workspace update event" ,
slog . F ( "workspace_id" , event . WorkspaceID ),
slog . F ( "event_kind" , event . Kind ), slog . Error ( err ))
return
}
msg , err := json . Marshal ( event )
if err != nil {
api . Logger . Warn ( ctx , "failed to marshal workspace update" ,
slog . F ( "workspace_id" , event . WorkspaceID ), slog . Error ( err ))
return
}
err = api . Pubsub . Publish ( wspubsub . WorkspaceEventChannel ( ownerID ), msg )
2022-11-07 07:25:18 -08:00
if err != nil {
api . Logger . Warn ( ctx , "failed to publish workspace update" ,
2024-11-01 14:17:05 +11:00
slog . F ( "workspace_id" , event . WorkspaceID ), slog . Error ( err ))
2022-11-07 07:25:18 -08:00
}
}
2023-06-16 17:14:22 +03:00
2023-07-28 09:57:23 -06:00
func ( api * API ) publishWorkspaceAgentLogsUpdate ( ctx context . Context , workspaceAgentID uuid . UUID , m agentsdk . LogsNotifyMessage ) {
2023-06-16 17:14:22 +03:00
b , err := json . Marshal ( m )
if err != nil {
2023-07-28 09:57:23 -06:00
api . Logger . Warn ( ctx , "failed to marshal logs notify message" , slog . F ( "workspace_agent_id" , workspaceAgentID ), slog . Error ( err ))
2023-06-16 17:14:22 +03:00
}
2023-07-28 09:57:23 -06:00
err = api . Pubsub . Publish ( agentsdk . LogsNotifyChannel ( workspaceAgentID ), b )
2023-06-16 17:14:22 +03:00
if err != nil {
2023-07-28 09:57:23 -06:00
api . Logger . Warn ( ctx , "failed to publish workspace agent logs update" , slog . F ( "workspace_agent_id" , workspaceAgentID ), slog . Error ( err ))
2023-06-16 17:14:22 +03:00
}
}
2025-07-31 09:05:09 -06:00
2025-08-07 10:14:58 -06:00
type WorkspaceACLUpdateValidator codersdk . UpdateWorkspaceACL
2025-07-31 09:05:09 -06:00
2025-08-07 10:14:58 -06:00
var (
workspaceACLUpdateUsersFieldName = "user_roles"
workspaceACLUpdateGroupsFieldName = "group_roles"
)
2025-07-31 09:05:09 -06:00
2025-08-07 10:14:58 -06:00
// WorkspaceACLUpdateValidator implements acl.UpdateValidator[codersdk.WorkspaceRole]
var _ acl . UpdateValidator [ codersdk . WorkspaceRole ] = WorkspaceACLUpdateValidator {}
2025-07-31 09:05:09 -06:00
2025-08-07 10:14:58 -06:00
func ( w WorkspaceACLUpdateValidator ) Users () ( map [ string ] codersdk . WorkspaceRole , string ) {
return w . UserRoles , workspaceACLUpdateUsersFieldName
2025-07-31 09:05:09 -06:00
}
2025-08-07 10:14:58 -06:00
func ( w WorkspaceACLUpdateValidator ) Groups () ( map [ string ] codersdk . WorkspaceRole , string ) {
return w . GroupRoles , workspaceACLUpdateGroupsFieldName
}
func ( WorkspaceACLUpdateValidator ) ValidateRole ( role codersdk . WorkspaceRole ) error {
2025-07-31 09:05:09 -06:00
actions := db2sdk . WorkspaceRoleActions ( role )
if len ( actions ) == 0 && role != codersdk . WorkspaceRoleDeleted {
2025-08-07 10:14:58 -06:00
return xerrors . Errorf ( "role %q is not a valid workspace role" , role )
2025-07-31 09:05:09 -06:00
}
return nil
}
// TODO: This will go here
// func convertToWorkspaceRole(actions []policy.Action) codersdk.TemplateRole {
// switch {
// case len(actions) == 2 && slice.SameElements(actions, []policy.Action{policy.ActionUse, policy.ActionRead}):
// return codersdk.TemplateRoleUse
// case len(actions) == 1 && actions[0] == policy.WildcardSymbol:
// return codersdk.TemplateRoleAdmin
// }
// return ""
// }