@Summary Post Workspace Usage by ID @ID post-workspace-usage-by-id @Security CoderSessionToken @Tags Workspaces @Accept json @Param workspace path string true "Workspace ID" format(uuid) @Param request body codersdk.PostWorkspaceUsageRequest false "Post workspace usage request" @Success 204 @Router
(rw http.ResponseWriter, r *http.Request)
| 1722 | // @Success 204 |
| 1723 | // @Router /api/v2/workspaces/{workspace}/usage [post] |
| 1724 | func (api *API) postWorkspaceUsage(rw http.ResponseWriter, r *http.Request) { |
| 1725 | workspace := httpmw.WorkspaceParam(r) |
| 1726 | if !api.Authorize(r, policy.ActionUpdate, workspace) { |
| 1727 | httpapi.Forbidden(rw) |
| 1728 | return |
| 1729 | } |
| 1730 | |
| 1731 | api.statsReporter.TrackUsage(workspace.ID) |
| 1732 | |
| 1733 | if !api.Experiments.Enabled(codersdk.ExperimentWorkspaceUsage) { |
| 1734 | // Continue previous behavior if the experiment is not enabled. |
| 1735 | rw.WriteHeader(http.StatusNoContent) |
| 1736 | return |
| 1737 | } |
| 1738 | |
| 1739 | if r.Body == http.NoBody { |
| 1740 | // Continue previous behavior if no body is present. |
| 1741 | rw.WriteHeader(http.StatusNoContent) |
| 1742 | return |
| 1743 | } |
| 1744 | |
| 1745 | ctx := r.Context() |
| 1746 | var req codersdk.PostWorkspaceUsageRequest |
| 1747 | if !httpapi.Read(ctx, rw, r, &req) { |
| 1748 | return |
| 1749 | } |
| 1750 | |
| 1751 | if req.AgentID == uuid.Nil && req.AppName == "" { |
| 1752 | // Continue previous behavior if body is empty. |
| 1753 | rw.WriteHeader(http.StatusNoContent) |
| 1754 | return |
| 1755 | } |
| 1756 | if req.AgentID == uuid.Nil { |
| 1757 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 1758 | Message: "Invalid request", |
| 1759 | Validations: []codersdk.ValidationError{{ |
| 1760 | Field: "agent_id", |
| 1761 | Detail: "must be set when app_name is set", |
| 1762 | }}, |
| 1763 | }) |
| 1764 | return |
| 1765 | } |
| 1766 | if req.AppName == "" { |
| 1767 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 1768 | Message: "Invalid request", |
| 1769 | Validations: []codersdk.ValidationError{{ |
| 1770 | Field: "app_name", |
| 1771 | Detail: "must be set when agent_id is set", |
| 1772 | }}, |
| 1773 | }) |
| 1774 | return |
| 1775 | } |
| 1776 | if !slices.Contains(codersdk.AllowedAppNames, req.AppName) { |
| 1777 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 1778 | Message: "Invalid request", |
| 1779 | Validations: []codersdk.ValidationError{{ |
| 1780 | Field: "app_name", |
| 1781 | Detail: fmt.Sprintf("must be one of %v", codersdk.AllowedAppNames), |
no test coverage detected