mirror of
https://github.com/coder/coder.git
synced 2026-11-02 21:50:08 +08:00
Populate `FeatureAgentRuntimeHours.Actual` on every entitlements refresh for licenses that grant the feature. A new `GetTotalUsageHBAgentRuntimeV1` query sums `runtime_ms` over the license's usage period, reading `usage_events` directly: `hb_agent_runtime_v1` is exactly one row per hourly bucket deployment-wide with `created_at` at the bucket start, enforced by the unique partial index introduced in #27983. The measurement reuses the shared `measureUsage` policy from #27984 through a new `AgentRuntimeMsFn` closure (usage publisher subject): failures publish the stable `LicenseAgentRuntimeUsageUnavailableErrorText` and log the cause. Usage is floored to whole hours, matching the unit of the `agent_runtime_hours_*` claims, and at most one warning is emitted per refresh: reaching the allocation supersedes the advisory soft limit. The dashboard renders the soft-limit advisory muted without a sales link and treats the runtime usage-unavailable text as a diagnostic. **Precise usage.** `Feature.ActualMs` (JSON `actual_ms`), set only for `agent_runtime_hours`, carries the exact stored milliseconds backing the floored `Actual` so clients can render fractional hours (e.g. `10.3`). It has the same freshness as `Actual`; the whole-hour warning thresholds are unchanged. **Unlimited licenses.** A license minted with the unlimited (`-1`) allocation decodes to an enabled feature with a nil `Limit` (#27984), so the warning write-back now guards the allocation dereference: no thresholds can exist for an unlimited license, so no runtime hours warning is ever emitted, while `Actual` is still measured and published. `Feature.Compare` is unchanged; for usage-period features the issued-at/end dates decide first, so a metered feature outranks an unlimited one only on an exact timestamp tie, an edge pinned by a `TestFeatureComparison` case and documented on `decodeAgentRuntimeHours`. **Grandfathered premium licenses.** Premium licenses without `agent_runtime_hours_*` claims are now granted the feature disabled with a zero limit over the license term, identical to an explicit `allocation: 0`: usage is measured and published for every Premium deployment, and chatd's pooled admission (#27902) caps concurrent agentic chats until a license with a positive allocation is added. The default carries a fixed early `UsagePeriod.IssuedAt` (2026-08-01, the same mechanism as the managed-agents default) so any license actually carrying the claims outranks it in the `AddFeature` merge regardless of the licenses' relative issue dates; the constant must stay earlier than the earliest legitimately issued claim-bearing license. Zero allocations (explicit or grandfathered) emit no deployment-wide warning banner: those deployments are steered by the in-page upgrade CTA and the concurrency cap. Enterprise licenses are unchanged. Part 3 of a 3-PR stack splitting up #27796 (see there for review history). Stack: #27983 → #27984 → this PR. Closes CODAGT-852.
144 lines
5.1 KiB
Go
144 lines
5.1 KiB
Go
package codersdk
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"golang.org/x/xerrors"
|
|
)
|
|
|
|
const (
|
|
LicenseExpiryClaim = "license_expires"
|
|
LicenseTelemetryRequiredErrorText = "License requires telemetry but telemetry is disabled"
|
|
LicenseManagedAgentLimitExceededWarningText = "You have built more workspaces with managed agents than your license allows."
|
|
LicenseAIGovernance90PercentWarningText = "You have used %d%% of your AI Governance add-on seats."
|
|
LicenseAIGovernanceOverLimitWarningText = "Your organization is using %d of %d AI Governance add-on seats (%d over the limit)."
|
|
// The dashboard's LicenseBanner matches this text's pre-placeholder
|
|
// prefix to render it muted and without a sales link, so the license
|
|
// warning texts must stay pairwise distinct before their first
|
|
// placeholder. See TestLicenseAgentRuntimeHoursWarningTexts.
|
|
LicenseAgentRuntimeHoursSoftLimitWarningText = "Your deployment is approaching its Coder Agent runtime hours allocation: %d of the %d hours included in the current license term are used, at or above the advisory soft limit of %d hours."
|
|
LicenseAgentRuntimeHoursAllocationReachedWarningText = "Your deployment has used %d of the %d Coder Agent runtime hours included in the current license term."
|
|
LicenseAgentRuntimeUsageUnavailableErrorText = "Unable to determine Coder Agent runtime usage. Reported runtime hours are unavailable until the next successful refresh; workspaces are unaffected. Check the coderd logs for details."
|
|
LicenseAgentRuntimeHoursClaimsIgnoredWarningText = "A license contains unusable Coder Agent runtime hour claims, which were ignored. The rest of that license is unaffected. Check the coderd logs for the affected license and claims, and contact support to have the license re-issued."
|
|
)
|
|
|
|
type AddLicenseRequest struct {
|
|
License string `json:"license" validate:"required"`
|
|
}
|
|
|
|
type License struct {
|
|
ID int32 `json:"id"`
|
|
UUID uuid.UUID `json:"uuid" format:"uuid"`
|
|
UploadedAt time.Time `json:"uploaded_at" format:"date-time"`
|
|
// Claims are the JWT claims asserted by the license. Here we use
|
|
// a generic string map to ensure that all data from the server is
|
|
// parsed verbatim, not just the fields this version of Coder
|
|
// understands.
|
|
Claims map[string]interface{} `json:"claims" table:"claims"`
|
|
}
|
|
|
|
// ExpiresAt returns the expiration time of the license.
|
|
// If the claim is missing or has an unexpected type, an error is returned.
|
|
func (l *License) ExpiresAt() (time.Time, error) {
|
|
expClaim, ok := l.Claims[LicenseExpiryClaim]
|
|
if !ok {
|
|
return time.Time{}, xerrors.New("license_expires claim is missing")
|
|
}
|
|
|
|
// This claim should be a unix timestamp.
|
|
// Everything is already an interface{}, so we need to do some type
|
|
// assertions to figure out what we're dealing with.
|
|
if unix, ok := expClaim.(json.Number); ok {
|
|
i64, err := unix.Int64()
|
|
if err != nil {
|
|
return time.Time{}, xerrors.Errorf("license_expires claim is not a valid unix timestamp: %w", err)
|
|
}
|
|
return time.Unix(i64, 0), nil
|
|
}
|
|
|
|
return time.Time{}, xerrors.Errorf("license_expires claim has unexpected type %T", expClaim)
|
|
}
|
|
|
|
func (l *License) Trial() bool {
|
|
if trial, ok := l.Claims["trial"].(bool); ok {
|
|
return trial
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (l *License) AllFeaturesClaim() bool {
|
|
if all, ok := l.Claims["all_features"].(bool); ok {
|
|
return all
|
|
}
|
|
return false
|
|
}
|
|
|
|
// FeaturesClaims provides the feature claims in license.
|
|
// This only returns the explicit claims. If checking for actual usage,
|
|
// also check `AllFeaturesClaim`.
|
|
func (l *License) FeaturesClaims() (map[FeatureName]int64, error) {
|
|
strMap, ok := l.Claims["features"].(map[string]interface{})
|
|
if !ok {
|
|
return nil, xerrors.New("features key is unexpected type")
|
|
}
|
|
fMap := make(map[FeatureName]int64)
|
|
for k, v := range strMap {
|
|
jn, ok := v.(json.Number)
|
|
if !ok {
|
|
return nil, xerrors.Errorf("feature %q has unexpected type", k)
|
|
}
|
|
|
|
n, err := jn.Int64()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
fMap[FeatureName(k)] = n
|
|
}
|
|
|
|
return fMap, nil
|
|
}
|
|
|
|
func (c *Client) AddLicense(ctx context.Context, r AddLicenseRequest) (License, error) {
|
|
res, err := c.Request(ctx, http.MethodPost, "/api/v2/licenses", r)
|
|
if err != nil {
|
|
return License{}, err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != http.StatusCreated {
|
|
return License{}, ReadBodyAsError(res)
|
|
}
|
|
var l License
|
|
return l, ReadBodyAsJSONUseNumber(res, &l)
|
|
}
|
|
|
|
func (c *Client) Licenses(ctx context.Context) ([]License, error) {
|
|
res, err := c.Request(ctx, http.MethodGet, "/api/v2/licenses", nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != http.StatusOK {
|
|
return nil, ReadBodyAsError(res)
|
|
}
|
|
var licenses []License
|
|
return licenses, ReadBodyAsJSONUseNumber(res, &licenses)
|
|
}
|
|
|
|
func (c *Client) DeleteLicense(ctx context.Context, id int32) error {
|
|
res, err := c.Request(ctx, http.MethodDelete, fmt.Sprintf("/api/v2/licenses/%d", id), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != http.StatusOK {
|
|
return ReadBodyAsError(res)
|
|
}
|
|
return nil
|
|
}
|