diff --git a/packages/api/internal/auth/middleware.go b/packages/api/internal/auth/middleware.go index f07cb8a34c..7cc18ae6d9 100644 --- a/packages/api/internal/auth/middleware.go +++ b/packages/api/internal/auth/middleware.go @@ -15,9 +15,9 @@ import ( "go.uber.org/zap" "github.com/e2b-dev/infra/packages/api/internal/api" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" "github.com/e2b-dev/infra/packages/api/internal/cfg" "github.com/e2b-dev/infra/packages/api/internal/db" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" ) @@ -134,13 +134,13 @@ func adminValidationFunction(adminToken string) func(context.Context, string) (s func CreateAuthenticationFunc( config cfg.Config, - teamValidationFunction func(context.Context, string) (authcache.AuthTeamInfo, *api.APIError), + teamValidationFunction func(context.Context, string) (*types.Team, *api.APIError), userValidationFunction func(context.Context, string) (uuid.UUID, *api.APIError), supabaseTokenValidationFunction func(context.Context, string) (uuid.UUID, *api.APIError), - supabaseTeamValidationFunction func(context.Context, string) (authcache.AuthTeamInfo, *api.APIError), + supabaseTeamValidationFunction func(context.Context, string) (*types.Team, *api.APIError), ) openapi3filter.AuthenticationFunc { authenticators := []authenticator{ - &commonAuthenticator[authcache.AuthTeamInfo]{ + &commonAuthenticator[*types.Team]{ securitySchemeName: "ApiKeyAuth", headerKey: headerKey{ name: "X-API-Key", @@ -173,7 +173,7 @@ func CreateAuthenticationFunc( contextKey: UserIDContextKey, errorMessage: "Invalid Supabase token.", }, - &commonAuthenticator[authcache.AuthTeamInfo]{ + &commonAuthenticator[*types.Team]{ securitySchemeName: "Supabase2TeamAuth", headerKey: headerKey{ name: "X-Supabase-Team", diff --git a/packages/api/internal/cache/auth/cache.go b/packages/api/internal/cache/auth/cache.go index d9887f41c2..1bf4b53816 100644 --- a/packages/api/internal/cache/auth/cache.go +++ b/packages/api/internal/cache/auth/cache.go @@ -8,7 +8,7 @@ import ( "github.com/jellydator/ttlcache/v3" "golang.org/x/sync/singleflight" - "github.com/e2b-dev/infra/packages/db/queries" + "github.com/e2b-dev/infra/packages/api/internal/db/types" ) const ( @@ -16,20 +16,14 @@ const ( refreshInterval = 1 * time.Minute ) -type AuthTeamInfo struct { - Team *queries.Team - Tier *queries.Tier -} - type TeamInfo struct { - team *queries.Team - tier *queries.Tier + team *types.Team lastRefresh time.Time once singleflight.Group } -type DataCallback = func(ctx context.Context, key string) (*queries.Team, *queries.Tier, error) +type DataCallback = func(ctx context.Context, key string) (*types.Team, error) type TeamAuthCache struct { cache *ttlcache.Cache[string, *TeamInfo] @@ -45,21 +39,21 @@ func NewTeamAuthCache() *TeamAuthCache { } // TODO: save blocked teams to cache as well, handle the condition in the GetOrSet method -func (c *TeamAuthCache) GetOrSet(ctx context.Context, key string, dataCallback DataCallback) (team *queries.Team, tier *queries.Tier, err error) { +func (c *TeamAuthCache) GetOrSet(ctx context.Context, key string, dataCallback DataCallback) (team *types.Team, err error) { var item *ttlcache.Item[string, *TeamInfo] var templateInfo *TeamInfo item = c.cache.Get(key) if item == nil { - team, tier, err = dataCallback(ctx, key) + team, err = dataCallback(ctx, key) if err != nil { - return nil, nil, fmt.Errorf("error while getting the team: %w", err) + return nil, fmt.Errorf("error while getting the team: %w", err) } - templateInfo = &TeamInfo{team: team, tier: tier, lastRefresh: time.Now()} + templateInfo = &TeamInfo{team: team, lastRefresh: time.Now()} c.cache.Set(key, templateInfo, authInfoExpiration) - return team, tier, nil + return team, nil } templateInfo = item.Value() @@ -70,7 +64,7 @@ func (c *TeamAuthCache) GetOrSet(ctx context.Context, key string, dataCallback D }) } - return templateInfo.team, templateInfo.tier, nil + return templateInfo.team, nil } // Refresh refreshes the cache for the given team ID. @@ -78,12 +72,12 @@ func (c *TeamAuthCache) Refresh(key string, dataCallback DataCallback) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - team, tier, err := dataCallback(ctx, key) + team, err := dataCallback(ctx, key) if err != nil { c.cache.Delete(key) return } - c.cache.Set(key, &TeamInfo{team: team, tier: tier, lastRefresh: time.Now()}, authInfoExpiration) + c.cache.Set(key, &TeamInfo{team: team, lastRefresh: time.Now()}, authInfoExpiration) } diff --git a/packages/api/internal/db/apikeys.go b/packages/api/internal/db/apikeys.go index 9755af670f..274628d60d 100644 --- a/packages/api/internal/db/apikeys.go +++ b/packages/api/internal/db/apikeys.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/e2b-dev/infra/packages/api/internal/db/types" sqlcdb "github.com/e2b-dev/infra/packages/db/client" "github.com/e2b-dev/infra/packages/db/queries" ) @@ -36,18 +37,19 @@ func validateTeamUsage(team queries.Team) error { return nil } -func GetTeamAuth(ctx context.Context, db *sqlcdb.Client, apiKey string) (*queries.Team, *queries.Tier, error) { +func GetTeamAuth(ctx context.Context, db *sqlcdb.Client, apiKey string) (*types.Team, error) { result, err := db.GetTeamWithTierByAPIKeyWithUpdateLastUsed(ctx, apiKey) if err != nil { errMsg := fmt.Errorf("failed to get team from API key: %w", err) - return nil, nil, errMsg + return nil, errMsg } err = validateTeamUsage(result.Team) if err != nil { - return nil, nil, err + return nil, err } - return &result.Team, &result.Tier, nil + team := types.NewTeam(&result.Team, &result.TeamLimit) + return team, nil } diff --git a/packages/api/internal/db/teams.go b/packages/api/internal/db/teams.go new file mode 100644 index 0000000000..fad98d3e7a --- /dev/null +++ b/packages/api/internal/db/teams.go @@ -0,0 +1,28 @@ +package db + +import ( + "context" + "fmt" + + "github.com/google/uuid" + + "github.com/e2b-dev/infra/packages/api/internal/db/types" + sqlcdb "github.com/e2b-dev/infra/packages/db/client" +) + +func GetTeamsByUser(ctx context.Context, db *sqlcdb.Client, userID uuid.UUID) ([]*types.TeamWithDefault, error) { + teams, err := db.GetTeamsWithUsersTeamsWithTier(ctx, userID) + if err != nil { + return nil, fmt.Errorf("error when getting default team: %w", err) + } + + teamsWithLimits := make([]*types.TeamWithDefault, 0, len(teams)) + for _, team := range teams { + teamsWithLimits = append(teamsWithLimits, &types.TeamWithDefault{ + Team: types.NewTeam(&team.Team, &team.TeamLimit), + IsDefault: team.UsersTeam.IsDefault, + }) + } + + return teamsWithLimits, nil +} diff --git a/packages/api/internal/db/types/limits.go b/packages/api/internal/db/types/limits.go new file mode 100644 index 0000000000..3438b1ea02 --- /dev/null +++ b/packages/api/internal/db/types/limits.go @@ -0,0 +1,11 @@ +package types + +type TeamLimits struct { + SandboxConcurrency int64 + BuildConcurrency int64 + MaxLengthHours int64 + + MaxVcpu int64 + MaxRamMb int64 + DiskMb int64 +} diff --git a/packages/api/internal/db/types/teams.go b/packages/api/internal/db/types/teams.go new file mode 100644 index 0000000000..1f305a81be --- /dev/null +++ b/packages/api/internal/db/types/teams.go @@ -0,0 +1,40 @@ +package types + +import ( + "github.com/e2b-dev/infra/packages/db/queries" +) + +type Team struct { + *queries.Team + + Limits *TeamLimits +} + +func newTeamLimits( + teamLimits *queries.TeamLimit, +) *TeamLimits { + return &TeamLimits{ + SandboxConcurrency: int64(teamLimits.ConcurrentSandboxes), + BuildConcurrency: int64(teamLimits.ConcurrentTemplateBuilds), + MaxLengthHours: teamLimits.MaxLengthHours, + MaxVcpu: int64(teamLimits.MaxVcpu), + MaxRamMb: int64(teamLimits.MaxRamMb), + DiskMb: int64(teamLimits.DiskMb), + } +} + +func NewTeam( + team *queries.Team, + teamLimits *queries.TeamLimit, +) *Team { + return &Team{ + Team: team, + Limits: newTeamLimits(teamLimits), + } +} + +type TeamWithDefault struct { + *Team + + IsDefault bool +} diff --git a/packages/api/internal/db/user.go b/packages/api/internal/db/user.go index 099e4d3bc8..6508e56465 100644 --- a/packages/api/internal/db/user.go +++ b/packages/api/internal/db/user.go @@ -6,16 +6,17 @@ import ( "github.com/google/uuid" + "github.com/e2b-dev/infra/packages/api/internal/db/types" sqlcdb "github.com/e2b-dev/infra/packages/db/client" "github.com/e2b-dev/infra/packages/db/queries" ) -func GetTeamByIDAndUserIDAuth(ctx context.Context, db *sqlcdb.Client, teamID string, userID uuid.UUID) (*queries.Team, *queries.Tier, error) { +func GetTeamByIDAndUserIDAuth(ctx context.Context, db *sqlcdb.Client, teamID string, userID uuid.UUID) (*types.Team, error) { teamIDParsed, err := uuid.Parse(teamID) if err != nil { errMsg := fmt.Errorf("failed to parse team ID: %w", err) - return nil, nil, errMsg + return nil, errMsg } result, err := db.GetTeamWithTierByTeamAndUser(ctx, queries.GetTeamWithTierByTeamAndUserParams{ @@ -25,13 +26,14 @@ func GetTeamByIDAndUserIDAuth(ctx context.Context, db *sqlcdb.Client, teamID str if err != nil { errMsg := fmt.Errorf("failed to get team from teamID and userID key: %w", err) - return nil, nil, errMsg + return nil, errMsg } err = validateTeamUsage(result.Team) if err != nil { - return nil, nil, err + return nil, err } - return &result.Team, &result.Tier, nil + team := types.NewTeam(&result.Team, &result.TeamLimit) + return team, nil } diff --git a/packages/api/internal/handlers/auth.go b/packages/api/internal/handlers/auth.go index 1819a11c44..0dbe0c1fe8 100644 --- a/packages/api/internal/handlers/auth.go +++ b/packages/api/internal/handlers/auth.go @@ -10,19 +10,19 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" - "github.com/e2b-dev/infra/packages/db/queries" + dbapi "github.com/e2b-dev/infra/packages/api/internal/db" + "github.com/e2b-dev/infra/packages/api/internal/db/types" ) func (a *APIStore) GetUserID(c *gin.Context) uuid.UUID { return c.Value(auth.UserIDContextKey).(uuid.UUID) } -func (a *APIStore) GetUserAndTeams(c *gin.Context) (*uuid.UUID, []queries.GetTeamsWithUsersTeamsWithTierRow, error) { +func (a *APIStore) GetUserAndTeams(c *gin.Context) (*uuid.UUID, []*types.TeamWithDefault, error) { userID := a.GetUserID(c) ctx := c.Request.Context() - teams, err := a.sqlcDB.GetTeamsWithUsersTeamsWithTier(ctx, userID) + teams, err := dbapi.GetTeamsByUser(ctx, a.sqlcDB, userID) if err != nil { return nil, nil, fmt.Errorf("error when getting default team: %w", err) } @@ -30,81 +30,82 @@ func (a *APIStore) GetUserAndTeams(c *gin.Context) (*uuid.UUID, []queries.GetTea return &userID, teams, err } -func (a *APIStore) GetTeamInfo(c *gin.Context) authcache.AuthTeamInfo { - return c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo) +func (a *APIStore) GetTeamInfo(c *gin.Context) *types.Team { + return c.Value(auth.TeamContextKey).(*types.Team) } -func (a *APIStore) GetTeamAndTier( +func (a *APIStore) GetTeamAndLimits( c *gin.Context, // Deprecated: use API Token authentication instead. teamID *string, -) (*queries.Team, *queries.Tier, *api.APIError) { +) (*types.Team, *api.APIError) { _, span := tracer.Start(c.Request.Context(), "get-team-and-tier") defer span.End() if c.Value(auth.TeamContextKey) != nil { - teamInfo := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo) + teamInfo := c.Value(auth.TeamContextKey).(*types.Team) - return teamInfo.Team, teamInfo.Tier, nil + return teamInfo, nil } else if c.Value(auth.UserIDContextKey) != nil { _, teams, err := a.GetUserAndTeams(c) if err != nil { - return nil, nil, &api.APIError{ + return nil, &api.APIError{ Code: http.StatusInternalServerError, ClientMsg: "Error when getting user and teams", Err: err, } } - team, tier, err := findTeamAndTier(teams, teamID) + + team, err := findTeamAndLimits(teams, teamID) if err != nil { if teamID == nil { - return nil, nil, &api.APIError{ + return nil, &api.APIError{ Code: http.StatusInternalServerError, ClientMsg: "Default team not found", Err: err, } } - return nil, nil, &api.APIError{ + return nil, &api.APIError{ Code: http.StatusForbidden, ClientMsg: "You are not allowed to access this team", Err: err, } } - return team, tier, nil + return team, nil } - return nil, nil, &api.APIError{ + return nil, &api.APIError{ Code: http.StatusUnauthorized, ClientMsg: "You are not authenticated", Err: errors.New("invalid authentication context for team and tier"), } } -// findTeamAndTier finds the appropriate team and tier based on the provided teamID or returns the default team -func findTeamAndTier(teams []queries.GetTeamsWithUsersTeamsWithTierRow, teamID *string) (*queries.Team, *queries.Tier, error) { +// findTeamAndTier finds the appropriate team and limits based on the provided teamID or returns the default team +func findTeamAndLimits(teams []*types.TeamWithDefault, teamID *string) (*types.Team, error) { if teamID != nil { teamUUID, err := uuid.Parse(*teamID) if err != nil { - return nil, nil, fmt.Errorf("invalid team ID: %s", *teamID) + return nil, fmt.Errorf("invalid team ID: %s", *teamID) } for _, t := range teams { if t.Team.ID == teamUUID { - return &t.Team, &t.Tier, nil + return t.Team, nil } } - return nil, nil, fmt.Errorf("team '%s' not found", *teamID) + return nil, fmt.Errorf("team '%s' not found", *teamID) } // Find default team for _, t := range teams { - if t.UsersTeam.IsDefault { - return &t.Team, &t.Tier, nil + if t.IsDefault { + return t.Team, nil } } - return nil, nil, fmt.Errorf("default team not found") + return nil, fmt.Errorf("default team not found") } diff --git a/packages/api/internal/handlers/sandbox.go b/packages/api/internal/handlers/sandbox.go index 13399b8a47..f0289acb09 100644 --- a/packages/api/internal/handlers/sandbox.go +++ b/packages/api/internal/handlers/sandbox.go @@ -11,7 +11,7 @@ import ( "go.uber.org/zap" "github.com/e2b-dev/infra/packages/api/internal/api" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/db/queries" sbxlogger "github.com/e2b-dev/infra/packages/shared/pkg/logger/sandbox" "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" @@ -26,7 +26,7 @@ func (a *APIStore) startSandbox( envVars map[string]string, metadata map[string]string, alias string, - team authcache.AuthTeamInfo, + team *types.Team, build queries.EnvBuild, requestHeader *http.Header, isResume bool, @@ -68,9 +68,9 @@ func (a *APIStore) startSandbox( telemetry.ReportEvent(ctx, "Created sandbox") _, analyticsSpan := tracer.Start(ctx, "analytics") - a.posthog.IdentifyAnalyticsTeam(team.Team.ID.String(), team.Team.Name) + a.posthog.IdentifyAnalyticsTeam(team.ID.String(), team.Name) properties := a.posthog.GetPackageToPosthogProperties(requestHeader) - a.posthog.CreateAnalyticsTeamEvent(team.Team.ID.String(), "created_instance", + a.posthog.CreateAnalyticsTeamEvent(team.ID.String(), "created_instance", properties. Set("environment", build.EnvID). Set("instance_id", sandbox.SandboxID). @@ -91,7 +91,7 @@ func (a *APIStore) startSandbox( sbxlogger.E(&sbxlogger.SandboxMetadata{ SandboxID: sandbox.SandboxID, TemplateID: build.EnvID, - TeamID: team.Team.ID.String(), + TeamID: team.ID.String(), }).Info("Sandbox created", zap.String("end_time", endTime.Format("2006-01-02 15:04:05 -07:00"))) return sandbox.ToAPISandbox(), nil diff --git a/packages/api/internal/handlers/sandbox_create.go b/packages/api/internal/handlers/sandbox_create.go index bb52025e02..78ca0674c3 100644 --- a/packages/api/internal/handlers/sandbox_create.go +++ b/packages/api/internal/handlers/sandbox_create.go @@ -13,7 +13,7 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/middleware/otel/metrics" "github.com/e2b-dev/infra/packages/api/internal/sandbox" "github.com/e2b-dev/infra/packages/api/internal/utils" @@ -43,7 +43,7 @@ func (a *APIStore) PostSandboxes(c *gin.Context) { ctx := c.Request.Context() // Get team from context, use TeamContextKey - teamInfo := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo) + teamInfo := c.Value(auth.TeamContextKey).(*types.Team) c.Set("teamID", teamInfo.Team.ID.String()) @@ -124,8 +124,8 @@ func (a *APIStore) PostSandboxes(c *gin.Context) { if body.Timeout != nil { timeout = time.Duration(*body.Timeout) * time.Second - if timeout > time.Duration(teamInfo.Tier.MaxLengthHours)*time.Hour { - a.sendAPIStoreError(c, http.StatusBadRequest, fmt.Sprintf("Timeout cannot be greater than %d hours", teamInfo.Tier.MaxLengthHours)) + if timeout > time.Duration(teamInfo.Limits.MaxLengthHours)*time.Hour { + a.sendAPIStoreError(c, http.StatusBadRequest, fmt.Sprintf("Timeout cannot be greater than %d hours", teamInfo.Limits.MaxLengthHours)) return } } diff --git a/packages/api/internal/handlers/sandbox_get.go b/packages/api/internal/handlers/sandbox_get.go index ff8e57c790..88b0e3398f 100644 --- a/packages/api/internal/handlers/sandbox_get.go +++ b/packages/api/internal/handlers/sandbox_get.go @@ -9,7 +9,7 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/sandbox" "github.com/e2b-dev/infra/packages/api/internal/utils" "github.com/e2b-dev/infra/packages/db/queries" @@ -21,7 +21,7 @@ import ( func (a *APIStore) GetSandboxesSandboxID(c *gin.Context, id string) { ctx := c.Request.Context() - teamInfo := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo) + teamInfo := c.Value(auth.TeamContextKey).(*types.Team) team := teamInfo.Team telemetry.ReportEvent(ctx, "get sandbox") diff --git a/packages/api/internal/handlers/sandbox_kill.go b/packages/api/internal/handlers/sandbox_kill.go index 027ef8f974..0b7003be3e 100644 --- a/packages/api/internal/handlers/sandbox_kill.go +++ b/packages/api/internal/handlers/sandbox_kill.go @@ -12,7 +12,7 @@ import ( "go.uber.org/zap" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/orchestrator" "github.com/e2b-dev/infra/packages/api/internal/sandbox" template_manager "github.com/e2b-dev/infra/packages/api/internal/template-manager" @@ -75,7 +75,7 @@ func (a *APIStore) DeleteSandboxesSandboxID( ctx := c.Request.Context() sandboxID = utils.ShortID(sandboxID) - team := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo).Team + team := c.Value(auth.TeamContextKey).(*types.Team) teamID := team.ID telemetry.SetAttributes(ctx, diff --git a/packages/api/internal/handlers/sandbox_logs.go b/packages/api/internal/handlers/sandbox_logs.go index beae1012dc..7f894635c5 100644 --- a/packages/api/internal/handlers/sandbox_logs.go +++ b/packages/api/internal/handlers/sandbox_logs.go @@ -11,7 +11,7 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/utils" apiedge "github.com/e2b-dev/infra/packages/shared/pkg/http/edge" "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" @@ -21,14 +21,14 @@ func (a *APIStore) GetSandboxesSandboxIDLogs(c *gin.Context, sandboxID string, p ctx := c.Request.Context() sandboxID = utils.ShortID(sandboxID) - team := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo).Team + team := c.Value(auth.TeamContextKey).(*types.Team) telemetry.SetAttributes(ctx, attribute.String("instance.id", sandboxID), telemetry.WithTeamID(team.ID.String()), ) - /// Sandboxes living in a cluster + // Sandboxes living in a cluster sbxLogs, err := a.getClusterSandboxLogs(ctx, sandboxID, team.ID.String(), utils.WithClusterFallback(team.ClusterID), params.Limit, params.Start) if err != nil { a.sendAPIStoreError(c, int(err.Code), err.Message) diff --git a/packages/api/internal/handlers/sandbox_metrics.go b/packages/api/internal/handlers/sandbox_metrics.go index 3dd649003f..03109b7d9c 100644 --- a/packages/api/internal/handlers/sandbox_metrics.go +++ b/packages/api/internal/handlers/sandbox_metrics.go @@ -11,7 +11,7 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/utils" clickhouse "github.com/e2b-dev/infra/packages/clickhouse/pkg" featureflags "github.com/e2b-dev/infra/packages/shared/pkg/feature-flags" @@ -25,7 +25,7 @@ func (a *APIStore) GetSandboxesSandboxIDMetrics(c *gin.Context, sandboxID string defer span.End() sandboxID = utils.ShortID(sandboxID) - team := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo).Team + team := c.Value(auth.TeamContextKey).(*types.Team) metricsReadFlag, err := a.featureFlags.BoolFlag(ctx, featureflags.MetricsReadFlagName, featureflags.SandboxContext(sandboxID)) diff --git a/packages/api/internal/handlers/sandbox_resume.go b/packages/api/internal/handlers/sandbox_resume.go index 6ed08dcc9b..d07588c3c2 100644 --- a/packages/api/internal/handlers/sandbox_resume.go +++ b/packages/api/internal/handlers/sandbox_resume.go @@ -13,7 +13,7 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/sandbox" "github.com/e2b-dev/infra/packages/api/internal/utils" "github.com/e2b-dev/infra/packages/db/queries" @@ -26,7 +26,7 @@ func (a *APIStore) PostSandboxesSandboxIDResume(c *gin.Context, sandboxID api.Sa ctx := c.Request.Context() // Get team from context, use TeamContextKey - teamInfo := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo) + teamInfo := c.Value(auth.TeamContextKey).(*types.Team) span := trace.SpanFromContext(ctx) traceID := span.SpanContext().TraceID().String() @@ -47,8 +47,8 @@ func (a *APIStore) PostSandboxesSandboxIDResume(c *gin.Context, sandboxID api.Sa if body.Timeout != nil { timeout = time.Duration(*body.Timeout) * time.Second - if timeout > time.Duration(teamInfo.Tier.MaxLengthHours)*time.Hour { - a.sendAPIStoreError(c, http.StatusBadRequest, fmt.Sprintf("Timeout cannot be greater than %d hours", teamInfo.Tier.MaxLengthHours)) + if timeout > time.Duration(teamInfo.Limits.MaxLengthHours)*time.Hour { + a.sendAPIStoreError(c, http.StatusBadRequest, fmt.Sprintf("Timeout cannot be greater than %d hours", teamInfo.Limits.MaxLengthHours)) return } diff --git a/packages/api/internal/handlers/sandboxes_list.go b/packages/api/internal/handlers/sandboxes_list.go index 9128e6319d..4fc89366a1 100644 --- a/packages/api/internal/handlers/sandboxes_list.go +++ b/packages/api/internal/handlers/sandboxes_list.go @@ -15,11 +15,11 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/sandbox" "github.com/e2b-dev/infra/packages/api/internal/utils" "github.com/e2b-dev/infra/packages/db/queries" - "github.com/e2b-dev/infra/packages/db/types" + dbtypes "github.com/e2b-dev/infra/packages/db/types" "github.com/e2b-dev/infra/packages/shared/pkg/consts" "github.com/e2b-dev/infra/packages/shared/pkg/logger" "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" @@ -34,7 +34,7 @@ const ( func (a *APIStore) getPausedSandboxes(ctx context.Context, teamID uuid.UUID, runningSandboxesIDs []string, metadataFilter *map[string]string, limit int32, cursorTime time.Time, cursorID string) ([]utils.PaginatedSandbox, error) { // Apply limit + 1 to check if there are more results queryLimit := limit + 1 - queryMetadata := types.JSONBStringMap{} + queryMetadata := dbtypes.JSONBStringMap{} if metadataFilter != nil { queryMetadata = *metadataFilter } @@ -71,7 +71,7 @@ func (a *APIStore) GetSandboxes(c *gin.Context, params api.GetSandboxesParams) { ctx := c.Request.Context() telemetry.ReportEvent(ctx, "list sandboxes") - teamInfo := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo) + teamInfo := c.Value(auth.TeamContextKey).(*types.Team) team := teamInfo.Team a.posthog.IdentifyAnalyticsTeam(team.ID.String(), team.Name) @@ -99,7 +99,7 @@ func (a *APIStore) GetV2Sandboxes(c *gin.Context, params api.GetV2SandboxesParam ctx := c.Request.Context() telemetry.ReportEvent(ctx, "list sandboxes") - teamInfo := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo) + teamInfo := c.Value(auth.TeamContextKey).(*types.Team) team := teamInfo.Team a.posthog.IdentifyAnalyticsTeam(team.ID.String(), team.Name) diff --git a/packages/api/internal/handlers/sandboxes_list_metrics.go b/packages/api/internal/handlers/sandboxes_list_metrics.go index 2325f1ed1b..fe05ebe59c 100644 --- a/packages/api/internal/handlers/sandboxes_list_metrics.go +++ b/packages/api/internal/handlers/sandboxes_list_metrics.go @@ -12,7 +12,7 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/utils" featureflags "github.com/e2b-dev/infra/packages/shared/pkg/feature-flags" "github.com/e2b-dev/infra/packages/shared/pkg/logger" @@ -82,7 +82,7 @@ func (a *APIStore) GetSandboxesMetrics(c *gin.Context, params api.GetSandboxesMe ctx := c.Request.Context() telemetry.ReportEvent(ctx, "list running instances with metrics") - team := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo).Team + team := c.Value(auth.TeamContextKey).(*types.Team) if len(params.SandboxIds) > maxSandboxMetricsCount { zap.L().Error("Too many sandboxes requested", zap.Int("requested_count", len(params.SandboxIds)), zap.Int("max_count", maxSandboxMetricsCount), logger.WithTeamID(team.ID.String())) diff --git a/packages/api/internal/handlers/store.go b/packages/api/internal/handlers/store.go index 5fabd0c9e1..25b90364d1 100644 --- a/packages/api/internal/handlers/store.go +++ b/packages/api/internal/handlers/store.go @@ -21,6 +21,7 @@ import ( templatecache "github.com/e2b-dev/infra/packages/api/internal/cache/templates" "github.com/e2b-dev/infra/packages/api/internal/cfg" dbapi "github.com/e2b-dev/infra/packages/api/internal/db" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/edge" "github.com/e2b-dev/infra/packages/api/internal/orchestrator" "github.com/e2b-dev/infra/packages/api/internal/sandbox" @@ -28,7 +29,6 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/utils" clickhouse "github.com/e2b-dev/infra/packages/clickhouse/pkg" sqlcdb "github.com/e2b-dev/infra/packages/db/client" - "github.com/e2b-dev/infra/packages/db/queries" "github.com/e2b-dev/infra/packages/shared/pkg/db" featureflags "github.com/e2b-dev/infra/packages/shared/pkg/feature-flags" "github.com/e2b-dev/infra/packages/shared/pkg/keys" @@ -249,23 +249,23 @@ func (a *APIStore) GetHealth(c *gin.Context) { c.String(http.StatusServiceUnavailable, "Service is unavailable") } -func (a *APIStore) GetTeamFromAPIKey(ctx context.Context, apiKey string) (authcache.AuthTeamInfo, *api.APIError) { +func (a *APIStore) GetTeamFromAPIKey(ctx context.Context, apiKey string) (*types.Team, *api.APIError) { hashedApiKey, err := keys.VerifyKey(keys.ApiKeyPrefix, apiKey) if err != nil { - return authcache.AuthTeamInfo{}, &api.APIError{ + return nil, &api.APIError{ Err: fmt.Errorf("failed to verify api key: %w", err), ClientMsg: "Invalid API key format", Code: http.StatusUnauthorized, } } - team, tier, err := a.authCache.GetOrSet(ctx, hashedApiKey, func(ctx context.Context, key string) (*queries.Team, *queries.Tier, error) { + team, err := a.authCache.GetOrSet(ctx, hashedApiKey, func(ctx context.Context, key string) (*types.Team, error) { return dbapi.GetTeamAuth(ctx, a.sqlcDB, key) }) if err != nil { var usageErr *dbapi.TeamForbiddenError if errors.As(err, &usageErr) { - return authcache.AuthTeamInfo{}, &api.APIError{ + return nil, &api.APIError{ Err: err, ClientMsg: err.Error(), Code: http.StatusForbidden, @@ -274,24 +274,21 @@ func (a *APIStore) GetTeamFromAPIKey(ctx context.Context, apiKey string) (authca var blockedErr *dbapi.TeamBlockedError if errors.As(err, &blockedErr) { - return authcache.AuthTeamInfo{}, &api.APIError{ + return nil, &api.APIError{ Err: err, ClientMsg: err.Error(), Code: http.StatusForbidden, } } - return authcache.AuthTeamInfo{}, &api.APIError{ + return nil, &api.APIError{ Err: fmt.Errorf("failed to get the team from db for an api key: %w", err), ClientMsg: "Cannot get the team for the given API key", Code: http.StatusUnauthorized, } } - return authcache.AuthTeamInfo{ - Team: team, - Tier: tier, - }, nil + return team, nil } func (a *APIStore) GetUserFromAccessToken(ctx context.Context, accessToken string) (uuid.UUID, *api.APIError) { @@ -390,17 +387,17 @@ func (a *APIStore) GetUserIDFromSupabaseToken(_ context.Context, supabaseToken s return userIDParsed, nil } -func (a *APIStore) GetTeamFromSupabaseToken(ctx context.Context, teamID string) (authcache.AuthTeamInfo, *api.APIError) { +func (a *APIStore) GetTeamFromSupabaseToken(ctx context.Context, teamID string) (*types.Team, *api.APIError) { userID := a.GetUserID(middleware.GetGinContext(ctx)) cacheKey := fmt.Sprintf("%s-%s", userID.String(), teamID) - team, tier, err := a.authCache.GetOrSet(ctx, cacheKey, func(ctx context.Context, _ string) (*queries.Team, *queries.Tier, error) { + team, err := a.authCache.GetOrSet(ctx, cacheKey, func(ctx context.Context, _ string) (*types.Team, error) { return dbapi.GetTeamByIDAndUserIDAuth(ctx, a.sqlcDB, teamID, userID) }) if err != nil { var usageErr *dbapi.TeamForbiddenError if errors.As(err, &usageErr) { - return authcache.AuthTeamInfo{}, &api.APIError{ + return nil, &api.APIError{ Err: fmt.Errorf("failed getting team: %w", err), ClientMsg: fmt.Sprintf("Forbidden: %s", err.Error()), Code: http.StatusForbidden, @@ -409,22 +406,19 @@ func (a *APIStore) GetTeamFromSupabaseToken(ctx context.Context, teamID string) var blockedErr *dbapi.TeamBlockedError if errors.As(err, &blockedErr) { - return authcache.AuthTeamInfo{}, &api.APIError{ + return nil, &api.APIError{ Err: fmt.Errorf("failed getting team: %w", err), ClientMsg: fmt.Sprintf("Blocked: %s", err.Error()), Code: http.StatusForbidden, } } - return authcache.AuthTeamInfo{}, &api.APIError{ + return nil, &api.APIError{ Err: fmt.Errorf("failed getting team: %w", err), ClientMsg: "Backend authentication failed", Code: http.StatusUnauthorized, } } - return authcache.AuthTeamInfo{ - Team: team, - Tier: tier, - }, nil + return team, nil } diff --git a/packages/api/internal/handlers/team_metrics.go b/packages/api/internal/handlers/team_metrics.go index 5017e0114f..fba70552b4 100644 --- a/packages/api/internal/handlers/team_metrics.go +++ b/packages/api/internal/handlers/team_metrics.go @@ -10,7 +10,7 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/utils" featureflags "github.com/e2b-dev/infra/packages/shared/pkg/feature-flags" "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" @@ -23,7 +23,7 @@ func (a *APIStore) GetTeamsTeamIDMetrics(c *gin.Context, teamID string, params a ctx, span := tracer.Start(ctx, "team-metrics") defer span.End() - team := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo).Team + team := c.Value(auth.TeamContextKey).(*types.Team) if teamID != team.ID.String() { telemetry.ReportError(ctx, "team ids mismatch", fmt.Errorf("you (%s) are not authorized to access this team's (%s) metrics", team.ID, teamID), telemetry.WithTeamID(team.ID.String())) diff --git a/packages/api/internal/handlers/team_metrics_max.go b/packages/api/internal/handlers/team_metrics_max.go index 404b5fc07f..992a423c92 100644 --- a/packages/api/internal/handlers/team_metrics_max.go +++ b/packages/api/internal/handlers/team_metrics_max.go @@ -10,7 +10,7 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/metrics" "github.com/e2b-dev/infra/packages/api/internal/utils" clickhouse "github.com/e2b-dev/infra/packages/clickhouse/pkg" @@ -23,7 +23,7 @@ func (a *APIStore) GetTeamsTeamIDMetricsMax(c *gin.Context, teamID string, param ctx, span := tracer.Start(ctx, "team-metrics-max") defer span.End() - team := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo).Team + team := c.Value(auth.TeamContextKey).(*types.Team) if teamID != team.ID.String() { telemetry.ReportError(ctx, "team ids mismatch", fmt.Errorf("you (%s) are not authorized to access this team's (%s) metrics", team.ID, teamID), telemetry.WithTeamID(team.ID.String())) diff --git a/packages/api/internal/handlers/template_build_status.go b/packages/api/internal/handlers/template_build_status.go index 257daaddeb..b84ac060fd 100644 --- a/packages/api/internal/handlers/template_build_status.go +++ b/packages/api/internal/handlers/template_build_status.go @@ -44,7 +44,7 @@ func (a *APIStore) GetTemplatesTemplateIDBuildsBuildIDStatus(c *gin.Context, tem } infoTeamID := buildInfo.TeamID.String() - team, _, apiErr := a.GetTeamAndTier(c, &infoTeamID) + team, apiErr := a.GetTeamAndLimits(c, &infoTeamID) if apiErr != nil { a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) telemetry.ReportCriticalError(ctx, "error when getting team and tier", apiErr.Err) diff --git a/packages/api/internal/handlers/template_delete.go b/packages/api/internal/handlers/template_delete.go index 520fc8ed23..ccec998da8 100644 --- a/packages/api/internal/handlers/template_delete.go +++ b/packages/api/internal/handlers/template_delete.go @@ -59,7 +59,7 @@ func (a *APIStore) DeleteTemplatesTemplateID(c *gin.Context, aliasOrTemplateID a } dbTeamID := template.TeamID.String() - team, _, apiErr := a.GetTeamAndTier(c, &dbTeamID) + team, apiErr := a.GetTeamAndLimits(c, &dbTeamID) if apiErr != nil { a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) telemetry.ReportCriticalError(ctx, "error when getting team and tier", apiErr.Err) diff --git a/packages/api/internal/handlers/template_layer_files_upload.go b/packages/api/internal/handlers/template_layer_files_upload.go index 1c07a59fc5..950c7f2cb0 100644 --- a/packages/api/internal/handlers/template_layer_files_upload.go +++ b/packages/api/internal/handlers/template_layer_files_upload.go @@ -24,7 +24,7 @@ func (a *APIStore) GetTemplatesTemplateIDFilesHash(c *gin.Context, templateID ap } dbTeamID := templateDB.TeamID.String() - team, _, apiErr := a.GetTeamAndTier(c, &dbTeamID) + team, apiErr := a.GetTeamAndLimits(c, &dbTeamID) if apiErr != nil { a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) telemetry.ReportCriticalError(ctx, "error when getting team and tier", apiErr.Err) diff --git a/packages/api/internal/handlers/template_request_build.go b/packages/api/internal/handlers/template_request_build.go index 40ebe319c9..538ce9ada8 100644 --- a/packages/api/internal/handlers/template_request_build.go +++ b/packages/api/internal/handlers/template_request_build.go @@ -10,10 +10,10 @@ import ( "go.opentelemetry.io/otel/trace" "github.com/e2b-dev/infra/packages/api/internal/api" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/template" "github.com/e2b-dev/infra/packages/api/internal/utils" "github.com/e2b-dev/infra/packages/db/dberrors" - "github.com/e2b-dev/infra/packages/db/queries" "github.com/e2b-dev/infra/packages/shared/pkg/id" "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" ) @@ -31,10 +31,10 @@ func (a *APIStore) PostTemplates(c *gin.Context) { return } - team, tier, apiErr := a.GetTeamAndTier(c, body.TeamID) + team, apiErr := a.GetTeamAndLimits(c, body.TeamID) if apiErr != nil { a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) - telemetry.ReportCriticalError(ctx, "error when getting team and tier", apiErr.Err) + telemetry.ReportCriticalError(ctx, "error when getting team and limits", apiErr.Err) return } @@ -43,7 +43,7 @@ func (a *APIStore) PostTemplates(c *gin.Context) { templateID := id.Generate() span.SetAttributes(telemetry.WithTemplateID(templateID)) - template, apiErr := a.buildTemplate(ctx, userID, team, tier, templateID, body) + template, apiErr := a.buildTemplate(ctx, userID, team, templateID, body) if apiErr != nil { telemetry.ReportCriticalError(ctx, "error when requesting template build", apiErr.Err, telemetry.WithTemplateID(templateID)) a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) @@ -87,7 +87,7 @@ func (a *APIStore) PostTemplatesTemplateID(c *gin.Context, rawTemplateID api.Tem } span.SetAttributes(telemetry.WithTemplateID(templateID)) - team, tier, apiErr := a.GetTeamAndTier(c, body.TeamID) + team, apiErr := a.GetTeamAndLimits(c, body.TeamID) if apiErr != nil { a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) telemetry.ReportCriticalError(ctx, "error when getting team and tier", apiErr.Err) @@ -112,7 +112,7 @@ func (a *APIStore) PostTemplatesTemplateID(c *gin.Context, rawTemplateID api.Tem return } - template, apiErr := a.buildTemplate(ctx, userID, team, tier, templateID, body) + template, apiErr := a.buildTemplate(ctx, userID, team, templateID, body) if apiErr != nil { telemetry.ReportCriticalError(ctx, "error when requesting template build", apiErr.Err, telemetry.WithTemplateID(templateID)) a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) @@ -138,8 +138,7 @@ func (a *APIStore) PostTemplatesTemplateID(c *gin.Context, rawTemplateID api.Tem func (a *APIStore) buildTemplate( ctx context.Context, userID uuid.UUID, - team *queries.Team, - tier *queries.Tier, + team *types.Team, templateID api.TemplateID, body api.TemplateBuildRequest, ) (*template.RegisterBuildResponse, *api.APIError) { @@ -159,7 +158,6 @@ func (a *APIStore) buildTemplate( TemplateID: templateID, UserID: &userID, Team: team, - Tier: tier, Dockerfile: body.Dockerfile, Alias: body.Alias, StartCmd: body.StartCmd, diff --git a/packages/api/internal/handlers/template_request_build_v2.go b/packages/api/internal/handlers/template_request_build_v2.go index 6eecd785e3..be5fd1743d 100644 --- a/packages/api/internal/handlers/template_request_build_v2.go +++ b/packages/api/internal/handlers/template_request_build_v2.go @@ -30,10 +30,10 @@ func (a *APIStore) PostV2Templates(c *gin.Context) { telemetry.ReportEvent(ctx, "started environment build") // Prepare info for rebuilding env - team, tier, apiErr := a.GetTeamAndTier(c, body.TeamID) + team, apiErr := a.GetTeamAndLimits(c, body.TeamID) if apiErr != nil { a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) - telemetry.ReportCriticalError(ctx, "error when getting team and tier", apiErr.Err) + telemetry.ReportCriticalError(ctx, "error when getting team, limits", apiErr.Err) return } @@ -75,7 +75,6 @@ func (a *APIStore) PostV2Templates(c *gin.Context) { TemplateID: templateID, UserID: nil, Team: team, - Tier: tier, Alias: &body.Alias, CpuCount: body.CpuCount, MemoryMB: body.MemoryMB, diff --git a/packages/api/internal/handlers/template_start_build.go b/packages/api/internal/handlers/template_start_build.go index 0feff79008..9ee9928d55 100644 --- a/packages/api/internal/handlers/template_start_build.go +++ b/packages/api/internal/handlers/template_start_build.go @@ -12,6 +12,7 @@ import ( "go.opentelemetry.io/otel/attribute" "github.com/e2b-dev/infra/packages/api/internal/api" + "github.com/e2b-dev/infra/packages/api/internal/db/types" templatemanager "github.com/e2b-dev/infra/packages/api/internal/template-manager" apiutils "github.com/e2b-dev/infra/packages/api/internal/utils" "github.com/e2b-dev/infra/packages/db/queries" @@ -100,11 +101,11 @@ func (a *APIStore) PostTemplatesTemplateIDBuildsBuildID(c *gin.Context, template return } - var team *queries.Team + var team *types.Team // Check if the user has access to the template for _, t := range teams { if t.Team.ID == templateBuildDB.Env.TeamID { - team = &t.Team + team = t.Team break } } diff --git a/packages/api/internal/handlers/template_start_build_v2.go b/packages/api/internal/handlers/template_start_build_v2.go index 6c45d0ca0f..aaf3107e62 100644 --- a/packages/api/internal/handlers/template_start_build_v2.go +++ b/packages/api/internal/handlers/template_start_build_v2.go @@ -68,7 +68,7 @@ func (a *APIStore) PostV2TemplatesTemplateIDBuildsBuildID(c *gin.Context, templa } dbTeamID := templateBuildDB.Env.TeamID.String() - team, _, apiErr := a.GetTeamAndTier(c, &dbTeamID) + team, apiErr := a.GetTeamAndLimits(c, &dbTeamID) if apiErr != nil { a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) telemetry.ReportCriticalError(ctx, "error when getting team and tier", apiErr.Err) diff --git a/packages/api/internal/handlers/template_update.go b/packages/api/internal/handlers/template_update.go index 0e4d6b0027..b546b0737b 100644 --- a/packages/api/internal/handlers/template_update.go +++ b/packages/api/internal/handlers/template_update.go @@ -65,7 +65,7 @@ func (a *APIStore) PatchTemplatesTemplateID(c *gin.Context, aliasOrTemplateID ap } dbTeamID := template.TeamID.String() - team, _, apiErr := a.GetTeamAndTier(c, &dbTeamID) + team, apiErr := a.GetTeamAndLimits(c, &dbTeamID) if apiErr != nil { a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) telemetry.ReportCriticalError(ctx, "error when getting team and tier", apiErr.Err) diff --git a/packages/api/internal/handlers/templates_list.go b/packages/api/internal/handlers/templates_list.go index 6b112b5efb..248ce11715 100644 --- a/packages/api/internal/handlers/templates_list.go +++ b/packages/api/internal/handlers/templates_list.go @@ -15,7 +15,7 @@ import ( func (a *APIStore) GetTemplates(c *gin.Context, params api.GetTemplatesParams) { ctx := c.Request.Context() - team, _, apiErr := a.GetTeamAndTier(c, params.TeamID) + team, apiErr := a.GetTeamAndLimits(c, params.TeamID) if apiErr != nil { a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) telemetry.ReportCriticalError(ctx, "error when getting team and tier", apiErr.Err) diff --git a/packages/api/internal/middleware/launchdarkly.go b/packages/api/internal/middleware/launchdarkly.go index fafb690e49..b44126f522 100644 --- a/packages/api/internal/middleware/launchdarkly.go +++ b/packages/api/internal/middleware/launchdarkly.go @@ -6,7 +6,7 @@ import ( "github.com/launchdarkly/go-sdk-common/v3/ldcontext" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" featureflags "github.com/e2b-dev/infra/packages/shared/pkg/feature-flags" ) @@ -39,21 +39,19 @@ func createLaunchDarklyUserContext(c *gin.Context) (ldcontext.Context, bool) { } func createLaunchDarklyTeamContext(c *gin.Context) (ldcontext.Context, bool) { - authTeamInfo, ok := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo) + team, ok := c.Value(auth.TeamContextKey).(*types.Team) if !ok { return ldcontext.Context{}, false } var contexts []ldcontext.Context - if team := authTeamInfo.Team; team != nil { + if team != nil { contexts = append(contexts, featureflags.TeamContext(team.ID.String(), team.Name)) if clusterID := team.ClusterID; clusterID != nil { contexts = append(contexts, featureflags.ClusterContext(clusterID.String())) } - } - if tier := authTeamInfo.Tier; tier != nil { - contexts = append(contexts, featureflags.TierContext(tier.ID, tier.Name)) + contexts = append(contexts, featureflags.TierContext(team.Tier, team.Tier)) } if len(contexts) == 0 { diff --git a/packages/api/internal/orchestrator/create_instance.go b/packages/api/internal/orchestrator/create_instance.go index 7ab3b4bb6f..6f8ddbec3e 100644 --- a/packages/api/internal/orchestrator/create_instance.go +++ b/packages/api/internal/orchestrator/create_instance.go @@ -13,7 +13,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" "github.com/e2b-dev/infra/packages/api/internal/api" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/orchestrator/nodemanager" "github.com/e2b-dev/infra/packages/api/internal/orchestrator/placement" "github.com/e2b-dev/infra/packages/api/internal/sandbox" @@ -31,7 +31,7 @@ func (o *Orchestrator) CreateSandbox( sandboxID, executionID, alias string, - team authcache.AuthTeamInfo, + team *types.Team, build queries.EnvBuild, metadata map[string]string, envVars map[string]string, @@ -48,8 +48,11 @@ func (o *Orchestrator) CreateSandbox( ctx, childSpan := tracer.Start(ctx, "create-sandbox") defer childSpan.End() + // Calculate total concurrent instances including addons + totalConcurrentInstances := team.Limits.SandboxConcurrency + // Check if team has reached max instances - releaseTeamSandboxReservation, err := o.sandboxStore.Reserve(sandboxID, team.Team.ID, team.Tier.ConcurrentInstances) + releaseTeamSandboxReservation, err := o.sandboxStore.Reserve(sandboxID, team.ID, totalConcurrentInstances) if err != nil { var limitErr *sandbox.LimitExceededError var alreadyErr *sandbox.AlreadyBeingStartedError @@ -62,8 +65,8 @@ func (o *Orchestrator) CreateSandbox( Code: http.StatusTooManyRequests, ClientMsg: fmt.Sprintf( "you have reached the maximum number of concurrent E2B sandboxes (%d). If you need more, "+ - "please contact us at 'https://e2b.dev/docs/getting-help'", team.Tier.ConcurrentInstances), - Err: fmt.Errorf("team '%s' has reached the maximum number of instances (%d)", team.Team.ID, team.Tier.ConcurrentInstances), + "please contact us at 'https://e2b.dev/docs/getting-help'", totalConcurrentInstances), + Err: fmt.Errorf("team '%s' has reached the maximum number of instances (%d)", team.ID, totalConcurrentInstances), } case errors.As(err, &alreadyErr): if alreadyErr.StartResult != nil { @@ -128,13 +131,13 @@ func (o *Orchestrator) CreateSandbox( telemetry.ReportEvent(ctx, "Got FC version info") var sbxDomain *string - if team.Team.ClusterID != nil { - cluster, ok := o.clusters.GetClusterById(*team.Team.ClusterID) + if team.ClusterID != nil { + cluster, ok := o.clusters.GetClusterById(*team.ClusterID) if !ok { return sandbox.Sandbox{}, &api.APIError{ Code: http.StatusInternalServerError, ClientMsg: "Error while looking for sandbox cluster information", - Err: fmt.Errorf("cannot access cluster %s associated with team id %s that spawned sandbox %s", *team.Team.ClusterID, team.Team.ID, sandboxID), + Err: fmt.Errorf("cannot access cluster %s associated with team id %s that spawned sandbox %s", *team.ClusterID, team.ID, sandboxID), } } @@ -146,7 +149,7 @@ func (o *Orchestrator) CreateSandbox( BaseTemplateId: baseTemplateID, TemplateId: build.EnvID, Alias: &alias, - TeamId: team.Team.ID.String(), + TeamId: team.ID.String(), BuildId: build.ID.String(), SandboxId: sandboxID, ExecutionId: executionID, @@ -156,7 +159,7 @@ func (o *Orchestrator) CreateSandbox( Metadata: metadata, EnvVars: envVars, EnvdAccessToken: envdAuthToken, - MaxSandboxLength: team.Tier.MaxLengthHours, + MaxSandboxLength: team.Limits.MaxLengthHours, HugePages: features.HasHugePages(), RamMb: build.RamMb, Vcpu: build.Vcpu, @@ -174,14 +177,14 @@ func (o *Orchestrator) CreateSandbox( if isResume && nodeID != nil { telemetry.ReportEvent(ctx, "Placing sandbox on the node where the snapshot was taken") - clusterID := utils.WithClusterFallback(team.Team.ClusterID) + clusterID := utils.WithClusterFallback(team.ClusterID) node = o.GetNode(clusterID, *nodeID) if node != nil && node.Status() != api.NodeStatusReady { node = nil } } - nodeClusterID := utils.WithClusterFallback(team.Team.ClusterID) + nodeClusterID := utils.WithClusterFallback(team.ClusterID) clusterNodes := o.GetClusterNodes(nodeClusterID) algorithm := o.getPlacementAlgorithm(ctx) @@ -221,10 +224,10 @@ func (o *Orchestrator) CreateSandbox( consts.ClientID, &alias, executionID, - team.Team.ID, + team.ID, build.ID, metadata, - time.Duration(team.Tier.MaxLengthHours)*time.Hour, + time.Duration(team.Limits.MaxLengthHours)*time.Hour, startTime, endTime, build.Vcpu, diff --git a/packages/api/internal/team/limits.go b/packages/api/internal/team/limits.go index 4310a3e736..58a528f201 100644 --- a/packages/api/internal/team/limits.go +++ b/packages/api/internal/team/limits.go @@ -6,10 +6,10 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/constants" - "github.com/e2b-dev/infra/packages/db/queries" + "github.com/e2b-dev/infra/packages/api/internal/db/types" ) -func LimitResources(tier *queries.Tier, cpuCount, memoryMB *int32) (int64, int64, *api.APIError) { +func LimitResources(limits *types.TeamLimits, cpuCount, memoryMB *int32) (int64, int64, *api.APIError) { cpu := constants.DefaultTemplateCPU ramMB := constants.DefaultTemplateMemory @@ -23,10 +23,10 @@ func LimitResources(tier *queries.Tier, cpuCount, memoryMB *int32) (int64, int64 } } - if cpu > tier.MaxVcpu { + if cpu > limits.MaxVcpu { return 0, 0, &api.APIError{ - Err: fmt.Errorf("CPU count exceeds team limits (%d)", tier.MaxVcpu), - ClientMsg: fmt.Sprintf("CPU count can't be higher than %d (if you need to increase this limit, please contact support)", tier.MaxVcpu), + Err: fmt.Errorf("CPU count exceeds team limits (%d)", limits.MaxVcpu), + ClientMsg: fmt.Sprintf("CPU count can't be higher than %d (if you need to increase this limit, please contact support)", limits.MaxVcpu), Code: http.StatusBadRequest, } } @@ -51,10 +51,10 @@ func LimitResources(tier *queries.Tier, cpuCount, memoryMB *int32) (int64, int64 } } - if ramMB > tier.MaxRamMb { + if ramMB > limits.MaxRamMb { return 0, 0, &api.APIError{ - Err: fmt.Errorf("memory exceeds team limits (%d MiB)", tier.MaxRamMb), - ClientMsg: fmt.Sprintf("Memory can't be higher than %d MiB (if you need to increase this limit, please contact support)", tier.MaxRamMb), + Err: fmt.Errorf("memory exceeds team limits (%d MiB)", limits.MaxRamMb), + ClientMsg: fmt.Sprintf("Memory can't be higher than %d MiB (if you need to increase this limit, please contact support)", limits.MaxRamMb), Code: http.StatusBadRequest, } } diff --git a/packages/api/internal/template/register_build.go b/packages/api/internal/template/register_build.go index 274ce305e2..9c82a7dfa4 100644 --- a/packages/api/internal/template/register_build.go +++ b/packages/api/internal/template/register_build.go @@ -13,8 +13,8 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" templatecache "github.com/e2b-dev/infra/packages/api/internal/cache/templates" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/team" - "github.com/e2b-dev/infra/packages/db/queries" "github.com/e2b-dev/infra/packages/shared/pkg/consts" "github.com/e2b-dev/infra/packages/shared/pkg/db" "github.com/e2b-dev/infra/packages/shared/pkg/id" @@ -35,8 +35,7 @@ type RegisterBuildData struct { BuilderNodeID string TemplateID api.TemplateID UserID *uuid.UUID - Team *queries.Team - Tier *queries.Tier + Team *types.Team Dockerfile string Alias *string StartCmd *string @@ -67,14 +66,16 @@ func RegisterBuild( teamBuildsExcludingCurrent := gutils.Filter(teamBuilds, func(item templatecache.TemplateBuildInfo) bool { return item.TemplateID != data.TemplateID }) - if len(teamBuildsExcludingCurrent) >= int(data.Tier.ConcurrentTemplateBuilds) { - telemetry.ReportError(ctx, "team has reached max concurrent template builds", nil, telemetry.WithTeamID(data.Team.ID.String()), attribute.Int64("tier.concurrent_template_builds", data.Tier.ConcurrentTemplateBuilds)) + + totalConcurrentTemplateBuilds := data.Team.Limits.BuildConcurrency + if len(teamBuildsExcludingCurrent) >= int(totalConcurrentTemplateBuilds) { + telemetry.ReportError(ctx, "team has reached max concurrent template builds", nil, telemetry.WithTeamID(data.Team.ID.String()), attribute.Int64("total.concurrent_template_builds", totalConcurrentTemplateBuilds)) return nil, &api.APIError{ Code: http.StatusTooManyRequests, ClientMsg: fmt.Sprintf( "you have reached the maximum number of concurrent template builds (%d). Please wait for existing builds to complete or contact support if you need more concurrent builds.", - data.Tier.ConcurrentTemplateBuilds), - Err: fmt.Errorf("team '%s' has reached the maximum number of concurrent template builds (%d)", data.Team.ID, data.Tier.ConcurrentTemplateBuilds), + totalConcurrentTemplateBuilds), + Err: fmt.Errorf("team '%s' has reached the maximum number of concurrent template builds (%d)", data.Team.ID, totalConcurrentTemplateBuilds), } } @@ -117,7 +118,7 @@ func RegisterBuild( telemetry.SetAttributes(ctx, attribute.Int("env.memory_mb", int(*data.MemoryMB))) } - cpuCount, ramMB, apiError := team.LimitResources(data.Tier, data.CpuCount, data.MemoryMB) + cpuCount, ramMB, apiError := team.LimitResources(data.Team.Limits, data.CpuCount, data.MemoryMB) if apiError != nil { telemetry.ReportCriticalError(ctx, "error when getting CPU and RAM", apiError.Err) return nil, apiError @@ -202,7 +203,7 @@ func RegisterBuild( SetVcpu(cpuCount). SetKernelVersion(schema.DefaultKernelVersion). SetFirecrackerVersion(schema.DefaultFirecrackerVersion). - SetFreeDiskSizeMB(data.Tier.DiskMb). + SetFreeDiskSizeMB(data.Team.Limits.DiskMb). SetNillableStartCmd(data.StartCmd). SetNillableReadyCmd(data.ReadyCmd). SetClusterNodeID(data.BuilderNodeID). diff --git a/packages/api/main.go b/packages/api/main.go index 938f368437..402a850a03 100644 --- a/packages/api/main.go +++ b/packages/api/main.go @@ -28,8 +28,8 @@ import ( "github.com/e2b-dev/infra/packages/api/internal/api" "github.com/e2b-dev/infra/packages/api/internal/auth" - authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth" "github.com/e2b-dev/infra/packages/api/internal/cfg" + "github.com/e2b-dev/infra/packages/api/internal/db/types" "github.com/e2b-dev/infra/packages/api/internal/handlers" customMiddleware "github.com/e2b-dev/infra/packages/api/internal/middleware" metricsMiddleware "github.com/e2b-dev/infra/packages/api/internal/middleware/otel/metrics" @@ -154,7 +154,7 @@ func NewGinServer(ctx context.Context, config cfg.Config, tel *telemetry.Client, // Get team from context, use TeamContextKey teamInfo := c.Value(auth.TeamContextKey) if teamInfo != nil { - teamID = teamInfo.(authcache.AuthTeamInfo).Team.ID.String() + teamID = teamInfo.(*types.Team).ID.String() } reqLogger := logger diff --git a/packages/db/migrations/20251011200438_create_addons_table.sql b/packages/db/migrations/20251011200438_create_addons_table.sql new file mode 100644 index 0000000000..a233d48d9d --- /dev/null +++ b/packages/db/migrations/20251011200438_create_addons_table.sql @@ -0,0 +1,66 @@ +-- +goose Up +-- +goose StatementBegin + +-- Create "addons" table +CREATE TABLE IF NOT EXISTS "public"."addons" +( + "id" uuid NOT NULL DEFAULT gen_random_uuid(), + "team_id" uuid NOT NULL, + "name" text NOT NULL, + "description" text NULL, + "extra_concurrent_sandboxes" bigint NOT NULL DEFAULT 0, + "extra_concurrent_template_builds" bigint NOT NULL DEFAULT 0, + "extra_max_vcpu" bigint NOT NULL DEFAULT 0, + "extra_max_ram_mb" bigint NOT NULL DEFAULT 0, + "extra_disk_mb" bigint NOT NULL DEFAULT 0, + "valid_from" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + "valid_to" timestamptz NULL , + "added_by" uuid NOT NULL, + PRIMARY KEY ("id"), + CONSTRAINT "addons_teams_addons" FOREIGN KEY ("team_id") REFERENCES "public"."teams" ("id") ON UPDATE NO ACTION ON DELETE CASCADE, + CONSTRAINT "addons_users_addons" FOREIGN KEY ("added_by") REFERENCES "auth"."users" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION, + CONSTRAINT "addons_valid_dates_check" CHECK (valid_to IS NULL OR valid_to > valid_from) +); + +-- Enable RLS for addons table +ALTER TABLE "public"."addons" ENABLE ROW LEVEL SECURITY; + +-- Create system user +INSERT INTO "auth"."users" (id, email) VALUES ('00000000-0000-0000-0000-000000000000', 'system@e2b.dev'); + +-- Create index on team_id for faster lookups +CREATE INDEX IF NOT EXISTS "addons_team_id_idx" ON "public"."addons" ("team_id"); + + +CREATE OR REPLACE VIEW "team_limits" +WITH (security_invoker=on) AS +SELECT + t.id, + tier.max_length_hours, + (tier.concurrent_instances + a.extra_concurrent_sandboxes) as concurrent_sandboxes, + (tier.concurrent_template_builds + a.extra_concurrent_template_builds) as concurrent_template_builds, + (tier.max_vcpu + a.extra_max_vcpu) as max_vcpu, + (tier.max_ram_mb + a.extra_max_ram_mb) as max_ram_mb, + (tier.disk_mb + a.extra_disk_mb) as disk_mb +FROM "public".teams t +JOIN "public"."tiers" tier on t.tier = tier.id +LEFT JOIN LATERAL ( + SELECT COALESCE(SUM(extra_concurrent_sandboxes),0)::bigint as extra_concurrent_sandboxes, + COALESCE(SUM(extra_concurrent_template_builds),0)::bigint as extra_concurrent_template_builds, + COALESCE(SUM(extra_max_vcpu),0)::bigint as extra_max_vcpu, + COALESCE(SUM(extra_max_ram_mb),0)::bigint as extra_max_ram_mb, + COALESCE(SUM(extra_disk_mb),0)::bigint as extra_disk_mb + FROM "public"."addons" addon + WHERE addon.team_id = t.id + AND addon.valid_from <= now() + AND (addon.valid_to IS NULL OR addon.valid_to > now()) + ) a ON true; +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin + +DROP VIEW IF EXISTS "team_limits"; +DROP TABLE IF EXISTS "public"."addons" CASCADE; + +-- +goose StatementEnd \ No newline at end of file diff --git a/packages/db/queries/get_team_tier_by_api_key.sql b/packages/db/queries/get_team_tier_by_api_key.sql deleted file mode 100644 index e0921b2731..0000000000 --- a/packages/db/queries/get_team_tier_by_api_key.sql +++ /dev/null @@ -1,8 +0,0 @@ --- name: GetTeamWithTierByAPIKeyWithUpdateLastUsed :one -UPDATE "public"."team_api_keys" tak -SET last_used = now() -FROM "public"."teams" t -JOIN "public"."tiers" tier ON t.tier = tier.id -WHERE tak.team_id = t.id - AND tak.api_key_hash = $1 -RETURNING sqlc.embed(t), sqlc.embed(tier); \ No newline at end of file diff --git a/packages/db/queries/get_team_tier_by_api_key.sql.go b/packages/db/queries/get_team_tier_by_api_key.sql.go deleted file mode 100644 index af2f59e2c0..0000000000 --- a/packages/db/queries/get_team_tier_by_api_key.sql.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 -// source: get_team_tier_by_api_key.sql - -package queries - -import ( - "context" -) - -const getTeamWithTierByAPIKeyWithUpdateLastUsed = `-- name: GetTeamWithTierByAPIKeyWithUpdateLastUsed :one -UPDATE "public"."team_api_keys" tak -SET last_used = now() -FROM "public"."teams" t -JOIN "public"."tiers" tier ON t.tier = tier.id -WHERE tak.team_id = t.id - AND tak.api_key_hash = $1 -RETURNING t.id, t.created_at, t.is_blocked, t.name, t.tier, t.email, t.is_banned, t.blocked_reason, t.cluster_id, tier.id, tier.name, tier.disk_mb, tier.concurrent_instances, tier.max_length_hours, tier.max_vcpu, tier.max_ram_mb, tier.concurrent_template_builds -` - -type GetTeamWithTierByAPIKeyWithUpdateLastUsedRow struct { - Team Team - Tier Tier -} - -func (q *Queries) GetTeamWithTierByAPIKeyWithUpdateLastUsed(ctx context.Context, apiKeyHash string) (GetTeamWithTierByAPIKeyWithUpdateLastUsedRow, error) { - row := q.db.QueryRow(ctx, getTeamWithTierByAPIKeyWithUpdateLastUsed, apiKeyHash) - var i GetTeamWithTierByAPIKeyWithUpdateLastUsedRow - err := row.Scan( - &i.Team.ID, - &i.Team.CreatedAt, - &i.Team.IsBlocked, - &i.Team.Name, - &i.Team.Tier, - &i.Team.Email, - &i.Team.IsBanned, - &i.Team.BlockedReason, - &i.Team.ClusterID, - &i.Tier.ID, - &i.Tier.Name, - &i.Tier.DiskMb, - &i.Tier.ConcurrentInstances, - &i.Tier.MaxLengthHours, - &i.Tier.MaxVcpu, - &i.Tier.MaxRamMb, - &i.Tier.ConcurrentTemplateBuilds, - ) - return i, err -} diff --git a/packages/db/queries/get_team_tier_by_team_and_user.sql b/packages/db/queries/get_team_tier_by_team_and_user.sql deleted file mode 100644 index e14dfed495..0000000000 --- a/packages/db/queries/get_team_tier_by_team_and_user.sql +++ /dev/null @@ -1,6 +0,0 @@ --- name: GetTeamWithTierByTeamAndUser :one -SELECT sqlc.embed(t), sqlc.embed(tier) -FROM "public"."teams" t -JOIN "public"."tiers" tier ON t.tier = tier.id -JOIN "public"."users_teams" ut ON ut.team_id = t.id -WHERE ut.user_id = $1 AND t.id = $2; diff --git a/packages/db/queries/get_team_tier_by_team_and_user.sql.go b/packages/db/queries/get_team_tier_by_team_and_user.sql.go deleted file mode 100644 index 9624279de3..0000000000 --- a/packages/db/queries/get_team_tier_by_team_and_user.sql.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 -// source: get_team_tier_by_team_and_user.sql - -package queries - -import ( - "context" - - "github.com/google/uuid" -) - -const getTeamWithTierByTeamAndUser = `-- name: GetTeamWithTierByTeamAndUser :one -SELECT t.id, t.created_at, t.is_blocked, t.name, t.tier, t.email, t.is_banned, t.blocked_reason, t.cluster_id, tier.id, tier.name, tier.disk_mb, tier.concurrent_instances, tier.max_length_hours, tier.max_vcpu, tier.max_ram_mb, tier.concurrent_template_builds -FROM "public"."teams" t -JOIN "public"."tiers" tier ON t.tier = tier.id -JOIN "public"."users_teams" ut ON ut.team_id = t.id -WHERE ut.user_id = $1 AND t.id = $2 -` - -type GetTeamWithTierByTeamAndUserParams struct { - UserID uuid.UUID - ID uuid.UUID -} - -type GetTeamWithTierByTeamAndUserRow struct { - Team Team - Tier Tier -} - -func (q *Queries) GetTeamWithTierByTeamAndUser(ctx context.Context, arg GetTeamWithTierByTeamAndUserParams) (GetTeamWithTierByTeamAndUserRow, error) { - row := q.db.QueryRow(ctx, getTeamWithTierByTeamAndUser, arg.UserID, arg.ID) - var i GetTeamWithTierByTeamAndUserRow - err := row.Scan( - &i.Team.ID, - &i.Team.CreatedAt, - &i.Team.IsBlocked, - &i.Team.Name, - &i.Team.Tier, - &i.Team.Email, - &i.Team.IsBanned, - &i.Team.BlockedReason, - &i.Team.ClusterID, - &i.Tier.ID, - &i.Tier.Name, - &i.Tier.DiskMb, - &i.Tier.ConcurrentInstances, - &i.Tier.MaxLengthHours, - &i.Tier.MaxVcpu, - &i.Tier.MaxRamMb, - &i.Tier.ConcurrentTemplateBuilds, - ) - return i, err -} diff --git a/packages/db/queries/models.go b/packages/db/queries/models.go index 018595779e..125ab1d328 100644 --- a/packages/db/queries/models.go +++ b/packages/db/queries/models.go @@ -25,6 +25,21 @@ type AccessToken struct { AccessTokenMaskSuffix string } +type Addon struct { + ID uuid.UUID + TeamID uuid.UUID + Name string + Description *string + ExtraConcurrentSandboxes int64 + ExtraConcurrentTemplateBuilds int64 + ExtraMaxVcpu int64 + ExtraMaxRamMb int64 + ExtraDiskMb int64 + ValidFrom time.Time + ValidTo *time.Time + AddedBy uuid.UUID +} + type AuthUser struct { ID uuid.UUID Email string @@ -123,6 +138,16 @@ type TeamApiKey struct { ApiKeyMaskSuffix string } +type TeamLimit struct { + ID uuid.UUID + MaxLengthHours int64 + ConcurrentSandboxes int32 + ConcurrentTemplateBuilds int32 + MaxVcpu int32 + MaxRamMb int32 + DiskMb int32 +} + type Tier struct { ID string Name string diff --git a/packages/db/queries/teams___tiers__usersteams.sql b/packages/db/queries/teams___tiers__usersteams.sql deleted file mode 100644 index 1ec67498f5..0000000000 --- a/packages/db/queries/teams___tiers__usersteams.sql +++ /dev/null @@ -1,6 +0,0 @@ --- name: GetTeamsWithUsersTeamsWithTier :many -SELECT sqlc.embed(t), sqlc.embed(ut), sqlc.embed(tier) -FROM "public"."teams" t -JOIN "public"."tiers" tier ON t.tier = tier.id -JOIN "public"."users_teams" ut ON ut.team_id = t.id -WHERE ut.user_id = $1; diff --git a/packages/db/queries/teams___tiers__usersteams.sql.go b/packages/db/queries/teams___tiers__usersteams.sql.go deleted file mode 100644 index 1afa7a446f..0000000000 --- a/packages/db/queries/teams___tiers__usersteams.sql.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.29.0 -// source: teams___tiers__usersteams.sql - -package queries - -import ( - "context" - - "github.com/google/uuid" -) - -const getTeamsWithUsersTeamsWithTier = `-- name: GetTeamsWithUsersTeamsWithTier :many -SELECT t.id, t.created_at, t.is_blocked, t.name, t.tier, t.email, t.is_banned, t.blocked_reason, t.cluster_id, ut.id, ut.user_id, ut.team_id, ut.is_default, ut.added_by, ut.created_at, tier.id, tier.name, tier.disk_mb, tier.concurrent_instances, tier.max_length_hours, tier.max_vcpu, tier.max_ram_mb, tier.concurrent_template_builds -FROM "public"."teams" t -JOIN "public"."tiers" tier ON t.tier = tier.id -JOIN "public"."users_teams" ut ON ut.team_id = t.id -WHERE ut.user_id = $1 -` - -type GetTeamsWithUsersTeamsWithTierRow struct { - Team Team - UsersTeam UsersTeam - Tier Tier -} - -func (q *Queries) GetTeamsWithUsersTeamsWithTier(ctx context.Context, userID uuid.UUID) ([]GetTeamsWithUsersTeamsWithTierRow, error) { - rows, err := q.db.Query(ctx, getTeamsWithUsersTeamsWithTier, userID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []GetTeamsWithUsersTeamsWithTierRow - for rows.Next() { - var i GetTeamsWithUsersTeamsWithTierRow - if err := rows.Scan( - &i.Team.ID, - &i.Team.CreatedAt, - &i.Team.IsBlocked, - &i.Team.Name, - &i.Team.Tier, - &i.Team.Email, - &i.Team.IsBanned, - &i.Team.BlockedReason, - &i.Team.ClusterID, - &i.UsersTeam.ID, - &i.UsersTeam.UserID, - &i.UsersTeam.TeamID, - &i.UsersTeam.IsDefault, - &i.UsersTeam.AddedBy, - &i.UsersTeam.CreatedAt, - &i.Tier.ID, - &i.Tier.Name, - &i.Tier.DiskMb, - &i.Tier.ConcurrentInstances, - &i.Tier.MaxLengthHours, - &i.Tier.MaxVcpu, - &i.Tier.MaxRamMb, - &i.Tier.ConcurrentTemplateBuilds, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} diff --git a/packages/db/queries/teams__get.sql b/packages/db/queries/teams__get.sql new file mode 100644 index 0000000000..935475b4c4 --- /dev/null +++ b/packages/db/queries/teams__get.sql @@ -0,0 +1,22 @@ +-- name: GetTeamWithTierByTeamAndUser :one +SELECT sqlc.embed(t), sqlc.embed(tl) +FROM "public"."teams" t +JOIN "public"."users_teams" ut ON ut.team_id = t.id +JOIN "public"."team_limits" tl on tl.id = t.id +WHERE ut.user_id = $1 AND t.id = $2; + +-- name: GetTeamsWithUsersTeamsWithTier :many +SELECT sqlc.embed(t), sqlc.embed(ut), sqlc.embed(tl) +FROM "public"."teams" t +JOIN "public"."users_teams" ut ON ut.team_id = t.id +JOIN "public"."team_limits" tl on tl.id = t.id +WHERE ut.user_id = $1; + +-- name: GetTeamWithTierByAPIKeyWithUpdateLastUsed :one +UPDATE "public"."team_api_keys" tak +SET last_used = now() +FROM "public"."teams" t +JOIN "public"."team_limits" tl on tl.id = t.id +WHERE tak.team_id = t.id + AND tak.api_key_hash = $1 +RETURNING sqlc.embed(t), sqlc.embed(tl); \ No newline at end of file diff --git a/packages/db/queries/teams__get.sql.go b/packages/db/queries/teams__get.sql.go new file mode 100644 index 0000000000..371c1aebd5 --- /dev/null +++ b/packages/db/queries/teams__get.sql.go @@ -0,0 +1,150 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: teams__get.sql + +package queries + +import ( + "context" + + "github.com/google/uuid" +) + +const getTeamWithTierByAPIKeyWithUpdateLastUsed = `-- name: GetTeamWithTierByAPIKeyWithUpdateLastUsed :one +UPDATE "public"."team_api_keys" tak +SET last_used = now() +FROM "public"."teams" t +JOIN "public"."team_limits" tl on tl.id = t.id +WHERE tak.team_id = t.id + AND tak.api_key_hash = $1 +RETURNING t.id, t.created_at, t.is_blocked, t.name, t.tier, t.email, t.is_banned, t.blocked_reason, t.cluster_id, tl.id, tl.max_length_hours, tl.concurrent_sandboxes, tl.concurrent_template_builds, tl.max_vcpu, tl.max_ram_mb, tl.disk_mb +` + +type GetTeamWithTierByAPIKeyWithUpdateLastUsedRow struct { + Team Team + TeamLimit TeamLimit +} + +func (q *Queries) GetTeamWithTierByAPIKeyWithUpdateLastUsed(ctx context.Context, apiKeyHash string) (GetTeamWithTierByAPIKeyWithUpdateLastUsedRow, error) { + row := q.db.QueryRow(ctx, getTeamWithTierByAPIKeyWithUpdateLastUsed, apiKeyHash) + var i GetTeamWithTierByAPIKeyWithUpdateLastUsedRow + err := row.Scan( + &i.Team.ID, + &i.Team.CreatedAt, + &i.Team.IsBlocked, + &i.Team.Name, + &i.Team.Tier, + &i.Team.Email, + &i.Team.IsBanned, + &i.Team.BlockedReason, + &i.Team.ClusterID, + &i.TeamLimit.ID, + &i.TeamLimit.MaxLengthHours, + &i.TeamLimit.ConcurrentSandboxes, + &i.TeamLimit.ConcurrentTemplateBuilds, + &i.TeamLimit.MaxVcpu, + &i.TeamLimit.MaxRamMb, + &i.TeamLimit.DiskMb, + ) + return i, err +} + +const getTeamWithTierByTeamAndUser = `-- name: GetTeamWithTierByTeamAndUser :one +SELECT t.id, t.created_at, t.is_blocked, t.name, t.tier, t.email, t.is_banned, t.blocked_reason, t.cluster_id, tl.id, tl.max_length_hours, tl.concurrent_sandboxes, tl.concurrent_template_builds, tl.max_vcpu, tl.max_ram_mb, tl.disk_mb +FROM "public"."teams" t +JOIN "public"."users_teams" ut ON ut.team_id = t.id +JOIN "public"."team_limits" tl on tl.id = t.id +WHERE ut.user_id = $1 AND t.id = $2 +` + +type GetTeamWithTierByTeamAndUserParams struct { + UserID uuid.UUID + ID uuid.UUID +} + +type GetTeamWithTierByTeamAndUserRow struct { + Team Team + TeamLimit TeamLimit +} + +func (q *Queries) GetTeamWithTierByTeamAndUser(ctx context.Context, arg GetTeamWithTierByTeamAndUserParams) (GetTeamWithTierByTeamAndUserRow, error) { + row := q.db.QueryRow(ctx, getTeamWithTierByTeamAndUser, arg.UserID, arg.ID) + var i GetTeamWithTierByTeamAndUserRow + err := row.Scan( + &i.Team.ID, + &i.Team.CreatedAt, + &i.Team.IsBlocked, + &i.Team.Name, + &i.Team.Tier, + &i.Team.Email, + &i.Team.IsBanned, + &i.Team.BlockedReason, + &i.Team.ClusterID, + &i.TeamLimit.ID, + &i.TeamLimit.MaxLengthHours, + &i.TeamLimit.ConcurrentSandboxes, + &i.TeamLimit.ConcurrentTemplateBuilds, + &i.TeamLimit.MaxVcpu, + &i.TeamLimit.MaxRamMb, + &i.TeamLimit.DiskMb, + ) + return i, err +} + +const getTeamsWithUsersTeamsWithTier = `-- name: GetTeamsWithUsersTeamsWithTier :many +SELECT t.id, t.created_at, t.is_blocked, t.name, t.tier, t.email, t.is_banned, t.blocked_reason, t.cluster_id, ut.id, ut.user_id, ut.team_id, ut.is_default, ut.added_by, ut.created_at, tl.id, tl.max_length_hours, tl.concurrent_sandboxes, tl.concurrent_template_builds, tl.max_vcpu, tl.max_ram_mb, tl.disk_mb +FROM "public"."teams" t +JOIN "public"."users_teams" ut ON ut.team_id = t.id +JOIN "public"."team_limits" tl on tl.id = t.id +WHERE ut.user_id = $1 +` + +type GetTeamsWithUsersTeamsWithTierRow struct { + Team Team + UsersTeam UsersTeam + TeamLimit TeamLimit +} + +func (q *Queries) GetTeamsWithUsersTeamsWithTier(ctx context.Context, userID uuid.UUID) ([]GetTeamsWithUsersTeamsWithTierRow, error) { + rows, err := q.db.Query(ctx, getTeamsWithUsersTeamsWithTier, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []GetTeamsWithUsersTeamsWithTierRow + for rows.Next() { + var i GetTeamsWithUsersTeamsWithTierRow + if err := rows.Scan( + &i.Team.ID, + &i.Team.CreatedAt, + &i.Team.IsBlocked, + &i.Team.Name, + &i.Team.Tier, + &i.Team.Email, + &i.Team.IsBanned, + &i.Team.BlockedReason, + &i.Team.ClusterID, + &i.UsersTeam.ID, + &i.UsersTeam.UserID, + &i.UsersTeam.TeamID, + &i.UsersTeam.IsDefault, + &i.UsersTeam.AddedBy, + &i.UsersTeam.CreatedAt, + &i.TeamLimit.ID, + &i.TeamLimit.MaxLengthHours, + &i.TeamLimit.ConcurrentSandboxes, + &i.TeamLimit.ConcurrentTemplateBuilds, + &i.TeamLimit.MaxVcpu, + &i.TeamLimit.MaxRamMb, + &i.TeamLimit.DiskMb, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/packages/shared/pkg/models/client.go b/packages/shared/pkg/models/client.go index 7fceaae5f0..0c1488bd76 100644 --- a/packages/shared/pkg/models/client.go +++ b/packages/shared/pkg/models/client.go @@ -23,7 +23,6 @@ import ( "github.com/e2b-dev/infra/packages/shared/pkg/models/envbuild" "github.com/e2b-dev/infra/packages/shared/pkg/models/snapshot" "github.com/e2b-dev/infra/packages/shared/pkg/models/team" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" "github.com/e2b-dev/infra/packages/shared/pkg/models/user" "github.com/e2b-dev/infra/packages/shared/pkg/models/usersteams" @@ -49,8 +48,6 @@ type Client struct { Snapshot *SnapshotClient // Team is the client for interacting with the Team builders. Team *TeamClient - // Tier is the client for interacting with the Tier builders. - Tier *TierClient // User is the client for interacting with the User builders. User *UserClient // UsersTeams is the client for interacting with the UsersTeams builders. @@ -73,7 +70,6 @@ func (c *Client) init() { c.EnvBuild = NewEnvBuildClient(c.config) c.Snapshot = NewSnapshotClient(c.config) c.Team = NewTeamClient(c.config) - c.Tier = NewTierClient(c.config) c.User = NewUserClient(c.config) c.UsersTeams = NewUsersTeamsClient(c.config) } @@ -178,7 +174,6 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { EnvBuild: NewEnvBuildClient(cfg), Snapshot: NewSnapshotClient(cfg), Team: NewTeamClient(cfg), - Tier: NewTierClient(cfg), User: NewUserClient(cfg), UsersTeams: NewUsersTeamsClient(cfg), }, nil @@ -207,7 +202,6 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) EnvBuild: NewEnvBuildClient(cfg), Snapshot: NewSnapshotClient(cfg), Team: NewTeamClient(cfg), - Tier: NewTierClient(cfg), User: NewUserClient(cfg), UsersTeams: NewUsersTeamsClient(cfg), }, nil @@ -240,7 +234,7 @@ func (c *Client) Close() error { func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ c.AccessToken, c.Cluster, c.Env, c.EnvAlias, c.EnvBuild, c.Snapshot, c.Team, - c.Tier, c.User, c.UsersTeams, + c.User, c.UsersTeams, } { n.Use(hooks...) } @@ -251,7 +245,7 @@ func (c *Client) Use(hooks ...Hook) { func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ c.AccessToken, c.Cluster, c.Env, c.EnvAlias, c.EnvBuild, c.Snapshot, c.Team, - c.Tier, c.User, c.UsersTeams, + c.User, c.UsersTeams, } { n.Intercept(interceptors...) } @@ -274,8 +268,6 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.Snapshot.mutate(ctx, m) case *TeamMutation: return c.Team.mutate(ctx, m) - case *TierMutation: - return c.Tier.mutate(ctx, m) case *UserMutation: return c.User.mutate(ctx, m) case *UsersTeamsMutation: @@ -1381,25 +1373,6 @@ func (c *TeamClient) QueryUsers(t *Team) *UserQuery { return query } -// QueryTeamTier queries the team_tier edge of a Team. -func (c *TeamClient) QueryTeamTier(t *Team) *TierQuery { - query := (&TierClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := t.ID - step := sqlgraph.NewStep( - sqlgraph.From(team.Table, team.FieldID, id), - sqlgraph.To(tier.Table, tier.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, team.TeamTierTable, team.TeamTierColumn), - ) - schemaConfig := t.schemaConfig - step.To.Schema = schemaConfig.Tier - step.Edge.Schema = schemaConfig.Team - fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) - return fromV, nil - } - return query -} - // QueryEnvs queries the envs edge of a Team. func (c *TeamClient) QueryEnvs(t *Team) *EnvQuery { query := (&EnvClient{config: c.config}).Query() @@ -1463,158 +1436,6 @@ func (c *TeamClient) mutate(ctx context.Context, m *TeamMutation) (Value, error) } } -// TierClient is a client for the Tier schema. -type TierClient struct { - config -} - -// NewTierClient returns a client for the Tier from the given config. -func NewTierClient(c config) *TierClient { - return &TierClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `tier.Hooks(f(g(h())))`. -func (c *TierClient) Use(hooks ...Hook) { - c.hooks.Tier = append(c.hooks.Tier, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `tier.Intercept(f(g(h())))`. -func (c *TierClient) Intercept(interceptors ...Interceptor) { - c.inters.Tier = append(c.inters.Tier, interceptors...) -} - -// Create returns a builder for creating a Tier entity. -func (c *TierClient) Create() *TierCreate { - mutation := newTierMutation(c.config, OpCreate) - return &TierCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of Tier entities. -func (c *TierClient) CreateBulk(builders ...*TierCreate) *TierCreateBulk { - return &TierCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *TierClient) MapCreateBulk(slice any, setFunc func(*TierCreate, int)) *TierCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &TierCreateBulk{err: fmt.Errorf("calling to TierClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*TierCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &TierCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for Tier. -func (c *TierClient) Update() *TierUpdate { - mutation := newTierMutation(c.config, OpUpdate) - return &TierUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *TierClient) UpdateOne(t *Tier) *TierUpdateOne { - mutation := newTierMutation(c.config, OpUpdateOne, withTier(t)) - return &TierUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *TierClient) UpdateOneID(id string) *TierUpdateOne { - mutation := newTierMutation(c.config, OpUpdateOne, withTierID(id)) - return &TierUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for Tier. -func (c *TierClient) Delete() *TierDelete { - mutation := newTierMutation(c.config, OpDelete) - return &TierDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *TierClient) DeleteOne(t *Tier) *TierDeleteOne { - return c.DeleteOneID(t.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *TierClient) DeleteOneID(id string) *TierDeleteOne { - builder := c.Delete().Where(tier.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &TierDeleteOne{builder} -} - -// Query returns a query builder for Tier. -func (c *TierClient) Query() *TierQuery { - return &TierQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeTier}, - inters: c.Interceptors(), - } -} - -// Get returns a Tier entity by its id. -func (c *TierClient) Get(ctx context.Context, id string) (*Tier, error) { - return c.Query().Where(tier.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *TierClient) GetX(ctx context.Context, id string) *Tier { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// QueryTeams queries the teams edge of a Tier. -func (c *TierClient) QueryTeams(t *Tier) *TeamQuery { - query := (&TeamClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := t.ID - step := sqlgraph.NewStep( - sqlgraph.From(tier.Table, tier.FieldID, id), - sqlgraph.To(team.Table, team.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, tier.TeamsTable, tier.TeamsColumn), - ) - schemaConfig := t.schemaConfig - step.To.Schema = schemaConfig.Team - step.Edge.Schema = schemaConfig.Team - fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// Hooks returns the client hooks. -func (c *TierClient) Hooks() []Hook { - return c.hooks.Tier -} - -// Interceptors returns the client interceptors. -func (c *TierClient) Interceptors() []Interceptor { - return c.inters.Tier -} - -func (c *TierClient) mutate(ctx context.Context, m *TierMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&TierCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&TierUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&TierUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&TierDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("models: unknown Tier mutation op: %q", m.Op()) - } -} - // UserClient is a client for the User schema. type UserClient struct { config @@ -1998,11 +1819,11 @@ func (c *UsersTeamsClient) mutate(ctx context.Context, m *UsersTeamsMutation) (V // hooks and interceptors per client, for fast access. type ( hooks struct { - AccessToken, Cluster, Env, EnvAlias, EnvBuild, Snapshot, Team, Tier, User, + AccessToken, Cluster, Env, EnvAlias, EnvBuild, Snapshot, Team, User, UsersTeams []ent.Hook } inters struct { - AccessToken, Cluster, Env, EnvAlias, EnvBuild, Snapshot, Team, Tier, User, + AccessToken, Cluster, Env, EnvAlias, EnvBuild, Snapshot, Team, User, UsersTeams []ent.Interceptor } ) @@ -2017,7 +1838,6 @@ var ( EnvBuild: tableSchemas[1], Snapshot: tableSchemas[1], Team: tableSchemas[1], - Tier: tableSchemas[1], User: tableSchemas[0], UsersTeams: tableSchemas[1], } diff --git a/packages/shared/pkg/models/ent.go b/packages/shared/pkg/models/ent.go index 3fc4d91259..7232e8bc6c 100644 --- a/packages/shared/pkg/models/ent.go +++ b/packages/shared/pkg/models/ent.go @@ -19,7 +19,6 @@ import ( "github.com/e2b-dev/infra/packages/shared/pkg/models/envbuild" "github.com/e2b-dev/infra/packages/shared/pkg/models/snapshot" "github.com/e2b-dev/infra/packages/shared/pkg/models/team" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" "github.com/e2b-dev/infra/packages/shared/pkg/models/user" "github.com/e2b-dev/infra/packages/shared/pkg/models/usersteams" ) @@ -89,7 +88,6 @@ func checkColumn(table, column string) error { envbuild.Table: envbuild.ValidColumn, snapshot.Table: snapshot.ValidColumn, team.Table: team.ValidColumn, - tier.Table: tier.ValidColumn, user.Table: user.ValidColumn, usersteams.Table: usersteams.ValidColumn, }) diff --git a/packages/shared/pkg/models/hook/hook.go b/packages/shared/pkg/models/hook/hook.go index d3e7e70900..b27544315c 100644 --- a/packages/shared/pkg/models/hook/hook.go +++ b/packages/shared/pkg/models/hook/hook.go @@ -93,18 +93,6 @@ func (f TeamFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *models.TeamMutation", m) } -// The TierFunc type is an adapter to allow the use of ordinary -// function as Tier mutator. -type TierFunc func(context.Context, *models.TierMutation) (models.Value, error) - -// Mutate calls f(ctx, m). -func (f TierFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { - if mv, ok := m.(*models.TierMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *models.TierMutation", m) -} - // The UserFunc type is an adapter to allow the use of ordinary // function as User mutator. type UserFunc func(context.Context, *models.UserMutation) (models.Value, error) diff --git a/packages/shared/pkg/models/internal/schemaconfig.go b/packages/shared/pkg/models/internal/schemaconfig.go index bc298fd2b3..4c8dfe9104 100644 --- a/packages/shared/pkg/models/internal/schemaconfig.go +++ b/packages/shared/pkg/models/internal/schemaconfig.go @@ -14,7 +14,6 @@ type SchemaConfig struct { EnvBuild string // EnvBuild table. Snapshot string // Snapshot table. Team string // Team table. - Tier string // Tier table. User string // User table. UsersTeams string // UsersTeams table. } diff --git a/packages/shared/pkg/models/migrate/schema.go b/packages/shared/pkg/models/migrate/schema.go index cee769c05c..9352fa0d75 100644 --- a/packages/shared/pkg/models/migrate/schema.go +++ b/packages/shared/pkg/models/migrate/schema.go @@ -174,38 +174,15 @@ var ( {Name: "is_blocked", Type: field.TypeBool, Nullable: true, Default: "false"}, {Name: "blocked_reason", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}}, {Name: "name", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}}, + {Name: "tier", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}}, {Name: "email", Type: field.TypeString, Size: 255, SchemaType: map[string]string{"postgres": "character varying(255)"}}, {Name: "cluster_id", Type: field.TypeUUID, Nullable: true, SchemaType: map[string]string{"postgres": "uuid"}}, - {Name: "tier", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}}, } // TeamsTable holds the schema information for the "teams" table. TeamsTable = &schema.Table{ Name: "teams", Columns: TeamsColumns, PrimaryKey: []*schema.Column{TeamsColumns[0]}, - ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "teams_tiers_teams", - Columns: []*schema.Column{TeamsColumns[8]}, - RefColumns: []*schema.Column{TiersColumns[0]}, - OnDelete: schema.NoAction, - }, - }, - } - // TiersColumns holds the columns for the "tiers" table. - TiersColumns = []*schema.Column{ - {Name: "id", Type: field.TypeString, Unique: true, SchemaType: map[string]string{"postgres": "text"}}, - {Name: "name", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}}, - {Name: "disk_mb", Type: field.TypeInt64, Default: "512"}, - {Name: "concurrent_instances", Type: field.TypeInt64, Comment: "The number of instances the team can run concurrently"}, - {Name: "concurrent_template_builds", Type: field.TypeInt64, Comment: "The number of concurrent template builds the team can run"}, - {Name: "max_length_hours", Type: field.TypeInt64}, - } - // TiersTable holds the schema information for the "tiers" table. - TiersTable = &schema.Table{ - Name: "tiers", - Columns: TiersColumns, - PrimaryKey: []*schema.Column{TiersColumns[0]}, } // UsersColumns holds the columns for the "users" table. UsersColumns = []*schema.Column{ @@ -261,7 +238,6 @@ var ( EnvBuildsTable, SnapshotsTable, TeamsTable, - TiersTable, UsersTable, UsersTeamsTable, } @@ -282,14 +258,7 @@ func init() { EnvBuildsTable.Annotation = &entsql.Annotation{} SnapshotsTable.ForeignKeys[0].RefTable = EnvsTable SnapshotsTable.Annotation = &entsql.Annotation{} - TeamsTable.ForeignKeys[0].RefTable = TiersTable TeamsTable.Annotation = &entsql.Annotation{} - TiersTable.Annotation = &entsql.Annotation{} - TiersTable.Annotation.Checks = map[string]string{ - "tiers_concurrent_sessions_check": "concurrent_instances > 0", - "tiers_concurrent_template_builds_check": "concurrent_template_builds > 0", - "tiers_disk_mb_check": "disk_mb > 0", - } UsersTable.Annotation = &entsql.Annotation{} UsersTeamsTable.ForeignKeys[0].RefTable = UsersTable UsersTeamsTable.ForeignKeys[1].RefTable = TeamsTable diff --git a/packages/shared/pkg/models/mutation.go b/packages/shared/pkg/models/mutation.go index d13227ab42..2c979f7495 100644 --- a/packages/shared/pkg/models/mutation.go +++ b/packages/shared/pkg/models/mutation.go @@ -19,7 +19,6 @@ import ( "github.com/e2b-dev/infra/packages/shared/pkg/models/predicate" "github.com/e2b-dev/infra/packages/shared/pkg/models/snapshot" "github.com/e2b-dev/infra/packages/shared/pkg/models/team" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" "github.com/e2b-dev/infra/packages/shared/pkg/models/user" "github.com/e2b-dev/infra/packages/shared/pkg/models/usersteams" "github.com/e2b-dev/infra/packages/shared/pkg/schema" @@ -42,7 +41,6 @@ const ( TypeEnvBuild = "EnvBuild" TypeSnapshot = "Snapshot" TypeTeam = "Team" - TypeTier = "Tier" TypeUser = "User" TypeUsersTeams = "UsersTeams" ) @@ -5522,14 +5520,13 @@ type TeamMutation struct { is_blocked *bool blocked_reason *string name *string + tier *string email *string cluster_id *uuid.UUID clearedFields map[string]struct{} users map[uuid.UUID]struct{} removedusers map[uuid.UUID]struct{} clearedusers bool - team_tier *string - clearedteam_tier bool envs map[string]struct{} removedenvs map[string]struct{} clearedenvs bool @@ -5866,12 +5863,12 @@ func (m *TeamMutation) ResetName() { // SetTier sets the "tier" field. func (m *TeamMutation) SetTier(s string) { - m.team_tier = &s + m.tier = &s } // Tier returns the value of the "tier" field in the mutation. func (m *TeamMutation) Tier() (r string, exists bool) { - v := m.team_tier + v := m.tier if v == nil { return } @@ -5897,7 +5894,7 @@ func (m *TeamMutation) OldTier(ctx context.Context) (v string, err error) { // ResetTier resets all changes to the "tier" field. func (m *TeamMutation) ResetTier() { - m.team_tier = nil + m.tier = nil } // SetEmail sets the "email" field. @@ -6039,46 +6036,6 @@ func (m *TeamMutation) ResetUsers() { m.removedusers = nil } -// SetTeamTierID sets the "team_tier" edge to the Tier entity by id. -func (m *TeamMutation) SetTeamTierID(id string) { - m.team_tier = &id -} - -// ClearTeamTier clears the "team_tier" edge to the Tier entity. -func (m *TeamMutation) ClearTeamTier() { - m.clearedteam_tier = true - m.clearedFields[team.FieldTier] = struct{}{} -} - -// TeamTierCleared reports if the "team_tier" edge to the Tier entity was cleared. -func (m *TeamMutation) TeamTierCleared() bool { - return m.clearedteam_tier -} - -// TeamTierID returns the "team_tier" edge ID in the mutation. -func (m *TeamMutation) TeamTierID() (id string, exists bool) { - if m.team_tier != nil { - return *m.team_tier, true - } - return -} - -// TeamTierIDs returns the "team_tier" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// TeamTierID instead. It exists only for internal usage by the builders. -func (m *TeamMutation) TeamTierIDs() (ids []string) { - if id := m.team_tier; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetTeamTier resets all changes to the "team_tier" edge. -func (m *TeamMutation) ResetTeamTier() { - m.team_tier = nil - m.clearedteam_tier = false -} - // AddEnvIDs adds the "envs" edge to the Env entity by ids. func (m *TeamMutation) AddEnvIDs(ids ...string) { if m.envs == nil { @@ -6237,7 +6194,7 @@ func (m *TeamMutation) Fields() []string { if m.name != nil { fields = append(fields, team.FieldName) } - if m.team_tier != nil { + if m.tier != nil { fields = append(fields, team.FieldTier) } if m.email != nil { @@ -6466,13 +6423,10 @@ func (m *TeamMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *TeamMutation) AddedEdges() []string { - edges := make([]string, 0, 4) + edges := make([]string, 0, 3) if m.users != nil { edges = append(edges, team.EdgeUsers) } - if m.team_tier != nil { - edges = append(edges, team.EdgeTeamTier) - } if m.envs != nil { edges = append(edges, team.EdgeEnvs) } @@ -6492,10 +6446,6 @@ func (m *TeamMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids - case team.EdgeTeamTier: - if id := m.team_tier; id != nil { - return []ent.Value{*id} - } case team.EdgeEnvs: ids := make([]ent.Value, 0, len(m.envs)) for id := range m.envs { @@ -6514,7 +6464,7 @@ func (m *TeamMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *TeamMutation) RemovedEdges() []string { - edges := make([]string, 0, 4) + edges := make([]string, 0, 3) if m.removedusers != nil { edges = append(edges, team.EdgeUsers) } @@ -6555,13 +6505,10 @@ func (m *TeamMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *TeamMutation) ClearedEdges() []string { - edges := make([]string, 0, 4) + edges := make([]string, 0, 3) if m.clearedusers { edges = append(edges, team.EdgeUsers) } - if m.clearedteam_tier { - edges = append(edges, team.EdgeTeamTier) - } if m.clearedenvs { edges = append(edges, team.EdgeEnvs) } @@ -6577,8 +6524,6 @@ func (m *TeamMutation) EdgeCleared(name string) bool { switch name { case team.EdgeUsers: return m.clearedusers - case team.EdgeTeamTier: - return m.clearedteam_tier case team.EdgeEnvs: return m.clearedenvs case team.EdgeUsersTeams: @@ -6591,9 +6536,6 @@ func (m *TeamMutation) EdgeCleared(name string) bool { // if that edge is not defined in the schema. func (m *TeamMutation) ClearEdge(name string) error { switch name { - case team.EdgeTeamTier: - m.ClearTeamTier() - return nil } return fmt.Errorf("unknown Team unique edge %s", name) } @@ -6605,9 +6547,6 @@ func (m *TeamMutation) ResetEdge(name string) error { case team.EdgeUsers: m.ResetUsers() return nil - case team.EdgeTeamTier: - m.ResetTeamTier() - return nil case team.EdgeEnvs: m.ResetEnvs() return nil @@ -6618,782 +6557,6 @@ func (m *TeamMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Team edge %s", name) } -// TierMutation represents an operation that mutates the Tier nodes in the graph. -type TierMutation struct { - config - op Op - typ string - id *string - name *string - disk_mb *int64 - adddisk_mb *int64 - concurrent_instances *int64 - addconcurrent_instances *int64 - concurrent_template_builds *int64 - addconcurrent_template_builds *int64 - max_length_hours *int64 - addmax_length_hours *int64 - clearedFields map[string]struct{} - teams map[uuid.UUID]struct{} - removedteams map[uuid.UUID]struct{} - clearedteams bool - done bool - oldValue func(context.Context) (*Tier, error) - predicates []predicate.Tier -} - -var _ ent.Mutation = (*TierMutation)(nil) - -// tierOption allows management of the mutation configuration using functional options. -type tierOption func(*TierMutation) - -// newTierMutation creates new mutation for the Tier entity. -func newTierMutation(c config, op Op, opts ...tierOption) *TierMutation { - m := &TierMutation{ - config: c, - op: op, - typ: TypeTier, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withTierID sets the ID field of the mutation. -func withTierID(id string) tierOption { - return func(m *TierMutation) { - var ( - err error - once sync.Once - value *Tier - ) - m.oldValue = func(ctx context.Context) (*Tier, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Tier.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withTier sets the old Tier of the mutation. -func withTier(node *Tier) tierOption { - return func(m *TierMutation) { - m.oldValue = func(context.Context) (*Tier, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m TierMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m TierMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("models: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Tier entities. -func (m *TierMutation) SetID(id string) { - m.id = &id -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *TierMutation) ID() (id string, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *TierMutation) IDs(ctx context.Context) ([]string, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []string{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().Tier.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetName sets the "name" field. -func (m *TierMutation) SetName(s string) { - m.name = &s -} - -// Name returns the value of the "name" field in the mutation. -func (m *TierMutation) Name() (r string, exists bool) { - v := m.name - if v == nil { - return - } - return *v, true -} - -// OldName returns the old "name" field's value of the Tier entity. -// If the Tier object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TierMutation) OldName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) - } - return oldValue.Name, nil -} - -// ResetName resets all changes to the "name" field. -func (m *TierMutation) ResetName() { - m.name = nil -} - -// SetDiskMB sets the "disk_mb" field. -func (m *TierMutation) SetDiskMB(i int64) { - m.disk_mb = &i - m.adddisk_mb = nil -} - -// DiskMB returns the value of the "disk_mb" field in the mutation. -func (m *TierMutation) DiskMB() (r int64, exists bool) { - v := m.disk_mb - if v == nil { - return - } - return *v, true -} - -// OldDiskMB returns the old "disk_mb" field's value of the Tier entity. -// If the Tier object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TierMutation) OldDiskMB(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDiskMB is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDiskMB requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDiskMB: %w", err) - } - return oldValue.DiskMB, nil -} - -// AddDiskMB adds i to the "disk_mb" field. -func (m *TierMutation) AddDiskMB(i int64) { - if m.adddisk_mb != nil { - *m.adddisk_mb += i - } else { - m.adddisk_mb = &i - } -} - -// AddedDiskMB returns the value that was added to the "disk_mb" field in this mutation. -func (m *TierMutation) AddedDiskMB() (r int64, exists bool) { - v := m.adddisk_mb - if v == nil { - return - } - return *v, true -} - -// ResetDiskMB resets all changes to the "disk_mb" field. -func (m *TierMutation) ResetDiskMB() { - m.disk_mb = nil - m.adddisk_mb = nil -} - -// SetConcurrentInstances sets the "concurrent_instances" field. -func (m *TierMutation) SetConcurrentInstances(i int64) { - m.concurrent_instances = &i - m.addconcurrent_instances = nil -} - -// ConcurrentInstances returns the value of the "concurrent_instances" field in the mutation. -func (m *TierMutation) ConcurrentInstances() (r int64, exists bool) { - v := m.concurrent_instances - if v == nil { - return - } - return *v, true -} - -// OldConcurrentInstances returns the old "concurrent_instances" field's value of the Tier entity. -// If the Tier object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TierMutation) OldConcurrentInstances(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldConcurrentInstances is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldConcurrentInstances requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldConcurrentInstances: %w", err) - } - return oldValue.ConcurrentInstances, nil -} - -// AddConcurrentInstances adds i to the "concurrent_instances" field. -func (m *TierMutation) AddConcurrentInstances(i int64) { - if m.addconcurrent_instances != nil { - *m.addconcurrent_instances += i - } else { - m.addconcurrent_instances = &i - } -} - -// AddedConcurrentInstances returns the value that was added to the "concurrent_instances" field in this mutation. -func (m *TierMutation) AddedConcurrentInstances() (r int64, exists bool) { - v := m.addconcurrent_instances - if v == nil { - return - } - return *v, true -} - -// ResetConcurrentInstances resets all changes to the "concurrent_instances" field. -func (m *TierMutation) ResetConcurrentInstances() { - m.concurrent_instances = nil - m.addconcurrent_instances = nil -} - -// SetConcurrentTemplateBuilds sets the "concurrent_template_builds" field. -func (m *TierMutation) SetConcurrentTemplateBuilds(i int64) { - m.concurrent_template_builds = &i - m.addconcurrent_template_builds = nil -} - -// ConcurrentTemplateBuilds returns the value of the "concurrent_template_builds" field in the mutation. -func (m *TierMutation) ConcurrentTemplateBuilds() (r int64, exists bool) { - v := m.concurrent_template_builds - if v == nil { - return - } - return *v, true -} - -// OldConcurrentTemplateBuilds returns the old "concurrent_template_builds" field's value of the Tier entity. -// If the Tier object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TierMutation) OldConcurrentTemplateBuilds(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldConcurrentTemplateBuilds is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldConcurrentTemplateBuilds requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldConcurrentTemplateBuilds: %w", err) - } - return oldValue.ConcurrentTemplateBuilds, nil -} - -// AddConcurrentTemplateBuilds adds i to the "concurrent_template_builds" field. -func (m *TierMutation) AddConcurrentTemplateBuilds(i int64) { - if m.addconcurrent_template_builds != nil { - *m.addconcurrent_template_builds += i - } else { - m.addconcurrent_template_builds = &i - } -} - -// AddedConcurrentTemplateBuilds returns the value that was added to the "concurrent_template_builds" field in this mutation. -func (m *TierMutation) AddedConcurrentTemplateBuilds() (r int64, exists bool) { - v := m.addconcurrent_template_builds - if v == nil { - return - } - return *v, true -} - -// ResetConcurrentTemplateBuilds resets all changes to the "concurrent_template_builds" field. -func (m *TierMutation) ResetConcurrentTemplateBuilds() { - m.concurrent_template_builds = nil - m.addconcurrent_template_builds = nil -} - -// SetMaxLengthHours sets the "max_length_hours" field. -func (m *TierMutation) SetMaxLengthHours(i int64) { - m.max_length_hours = &i - m.addmax_length_hours = nil -} - -// MaxLengthHours returns the value of the "max_length_hours" field in the mutation. -func (m *TierMutation) MaxLengthHours() (r int64, exists bool) { - v := m.max_length_hours - if v == nil { - return - } - return *v, true -} - -// OldMaxLengthHours returns the old "max_length_hours" field's value of the Tier entity. -// If the Tier object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TierMutation) OldMaxLengthHours(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMaxLengthHours is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMaxLengthHours requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMaxLengthHours: %w", err) - } - return oldValue.MaxLengthHours, nil -} - -// AddMaxLengthHours adds i to the "max_length_hours" field. -func (m *TierMutation) AddMaxLengthHours(i int64) { - if m.addmax_length_hours != nil { - *m.addmax_length_hours += i - } else { - m.addmax_length_hours = &i - } -} - -// AddedMaxLengthHours returns the value that was added to the "max_length_hours" field in this mutation. -func (m *TierMutation) AddedMaxLengthHours() (r int64, exists bool) { - v := m.addmax_length_hours - if v == nil { - return - } - return *v, true -} - -// ResetMaxLengthHours resets all changes to the "max_length_hours" field. -func (m *TierMutation) ResetMaxLengthHours() { - m.max_length_hours = nil - m.addmax_length_hours = nil -} - -// AddTeamIDs adds the "teams" edge to the Team entity by ids. -func (m *TierMutation) AddTeamIDs(ids ...uuid.UUID) { - if m.teams == nil { - m.teams = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.teams[ids[i]] = struct{}{} - } -} - -// ClearTeams clears the "teams" edge to the Team entity. -func (m *TierMutation) ClearTeams() { - m.clearedteams = true -} - -// TeamsCleared reports if the "teams" edge to the Team entity was cleared. -func (m *TierMutation) TeamsCleared() bool { - return m.clearedteams -} - -// RemoveTeamIDs removes the "teams" edge to the Team entity by IDs. -func (m *TierMutation) RemoveTeamIDs(ids ...uuid.UUID) { - if m.removedteams == nil { - m.removedteams = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.teams, ids[i]) - m.removedteams[ids[i]] = struct{}{} - } -} - -// RemovedTeams returns the removed IDs of the "teams" edge to the Team entity. -func (m *TierMutation) RemovedTeamsIDs() (ids []uuid.UUID) { - for id := range m.removedteams { - ids = append(ids, id) - } - return -} - -// TeamsIDs returns the "teams" edge IDs in the mutation. -func (m *TierMutation) TeamsIDs() (ids []uuid.UUID) { - for id := range m.teams { - ids = append(ids, id) - } - return -} - -// ResetTeams resets all changes to the "teams" edge. -func (m *TierMutation) ResetTeams() { - m.teams = nil - m.clearedteams = false - m.removedteams = nil -} - -// Where appends a list predicates to the TierMutation builder. -func (m *TierMutation) Where(ps ...predicate.Tier) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the TierMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TierMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Tier, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *TierMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *TierMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (Tier). -func (m *TierMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *TierMutation) Fields() []string { - fields := make([]string, 0, 5) - if m.name != nil { - fields = append(fields, tier.FieldName) - } - if m.disk_mb != nil { - fields = append(fields, tier.FieldDiskMB) - } - if m.concurrent_instances != nil { - fields = append(fields, tier.FieldConcurrentInstances) - } - if m.concurrent_template_builds != nil { - fields = append(fields, tier.FieldConcurrentTemplateBuilds) - } - if m.max_length_hours != nil { - fields = append(fields, tier.FieldMaxLengthHours) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *TierMutation) Field(name string) (ent.Value, bool) { - switch name { - case tier.FieldName: - return m.Name() - case tier.FieldDiskMB: - return m.DiskMB() - case tier.FieldConcurrentInstances: - return m.ConcurrentInstances() - case tier.FieldConcurrentTemplateBuilds: - return m.ConcurrentTemplateBuilds() - case tier.FieldMaxLengthHours: - return m.MaxLengthHours() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *TierMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case tier.FieldName: - return m.OldName(ctx) - case tier.FieldDiskMB: - return m.OldDiskMB(ctx) - case tier.FieldConcurrentInstances: - return m.OldConcurrentInstances(ctx) - case tier.FieldConcurrentTemplateBuilds: - return m.OldConcurrentTemplateBuilds(ctx) - case tier.FieldMaxLengthHours: - return m.OldMaxLengthHours(ctx) - } - return nil, fmt.Errorf("unknown Tier field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *TierMutation) SetField(name string, value ent.Value) error { - switch name { - case tier.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case tier.FieldDiskMB: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDiskMB(v) - return nil - case tier.FieldConcurrentInstances: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetConcurrentInstances(v) - return nil - case tier.FieldConcurrentTemplateBuilds: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetConcurrentTemplateBuilds(v) - return nil - case tier.FieldMaxLengthHours: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMaxLengthHours(v) - return nil - } - return fmt.Errorf("unknown Tier field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *TierMutation) AddedFields() []string { - var fields []string - if m.adddisk_mb != nil { - fields = append(fields, tier.FieldDiskMB) - } - if m.addconcurrent_instances != nil { - fields = append(fields, tier.FieldConcurrentInstances) - } - if m.addconcurrent_template_builds != nil { - fields = append(fields, tier.FieldConcurrentTemplateBuilds) - } - if m.addmax_length_hours != nil { - fields = append(fields, tier.FieldMaxLengthHours) - } - return fields -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *TierMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case tier.FieldDiskMB: - return m.AddedDiskMB() - case tier.FieldConcurrentInstances: - return m.AddedConcurrentInstances() - case tier.FieldConcurrentTemplateBuilds: - return m.AddedConcurrentTemplateBuilds() - case tier.FieldMaxLengthHours: - return m.AddedMaxLengthHours() - } - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *TierMutation) AddField(name string, value ent.Value) error { - switch name { - case tier.FieldDiskMB: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddDiskMB(v) - return nil - case tier.FieldConcurrentInstances: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddConcurrentInstances(v) - return nil - case tier.FieldConcurrentTemplateBuilds: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddConcurrentTemplateBuilds(v) - return nil - case tier.FieldMaxLengthHours: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddMaxLengthHours(v) - return nil - } - return fmt.Errorf("unknown Tier numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *TierMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *TierMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *TierMutation) ClearField(name string) error { - return fmt.Errorf("unknown Tier nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *TierMutation) ResetField(name string) error { - switch name { - case tier.FieldName: - m.ResetName() - return nil - case tier.FieldDiskMB: - m.ResetDiskMB() - return nil - case tier.FieldConcurrentInstances: - m.ResetConcurrentInstances() - return nil - case tier.FieldConcurrentTemplateBuilds: - m.ResetConcurrentTemplateBuilds() - return nil - case tier.FieldMaxLengthHours: - m.ResetMaxLengthHours() - return nil - } - return fmt.Errorf("unknown Tier field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *TierMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.teams != nil { - edges = append(edges, tier.EdgeTeams) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *TierMutation) AddedIDs(name string) []ent.Value { - switch name { - case tier.EdgeTeams: - ids := make([]ent.Value, 0, len(m.teams)) - for id := range m.teams { - ids = append(ids, id) - } - return ids - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *TierMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) - if m.removedteams != nil { - edges = append(edges, tier.EdgeTeams) - } - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *TierMutation) RemovedIDs(name string) []ent.Value { - switch name { - case tier.EdgeTeams: - ids := make([]ent.Value, 0, len(m.removedteams)) - for id := range m.removedteams { - ids = append(ids, id) - } - return ids - } - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TierMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.clearedteams { - edges = append(edges, tier.EdgeTeams) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *TierMutation) EdgeCleared(name string) bool { - switch name { - case tier.EdgeTeams: - return m.clearedteams - } - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *TierMutation) ClearEdge(name string) error { - switch name { - } - return fmt.Errorf("unknown Tier unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *TierMutation) ResetEdge(name string) error { - switch name { - case tier.EdgeTeams: - m.ResetTeams() - return nil - } - return fmt.Errorf("unknown Tier edge %s", name) -} - // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config diff --git a/packages/shared/pkg/models/predicate/predicate.go b/packages/shared/pkg/models/predicate/predicate.go index 90c44066a7..5f76caf69b 100644 --- a/packages/shared/pkg/models/predicate/predicate.go +++ b/packages/shared/pkg/models/predicate/predicate.go @@ -27,9 +27,6 @@ type Snapshot func(*sql.Selector) // Team is the predicate function for team builders. type Team func(*sql.Selector) -// Tier is the predicate function for tier builders. -type Tier func(*sql.Selector) - // User is the predicate function for user builders. type User func(*sql.Selector) diff --git a/packages/shared/pkg/models/team.go b/packages/shared/pkg/models/team.go index 8a11d18fc7..b6277df530 100644 --- a/packages/shared/pkg/models/team.go +++ b/packages/shared/pkg/models/team.go @@ -10,7 +10,6 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" "github.com/e2b-dev/infra/packages/shared/pkg/models/team" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" "github.com/google/uuid" ) @@ -45,15 +44,13 @@ type Team struct { type TeamEdges struct { // Users holds the value of the users edge. Users []*User `json:"users,omitempty"` - // TeamTier holds the value of the team_tier edge. - TeamTier *Tier `json:"team_tier,omitempty"` // Envs holds the value of the envs edge. Envs []*Env `json:"envs,omitempty"` // UsersTeams holds the value of the users_teams edge. UsersTeams []*UsersTeams `json:"users_teams,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [4]bool + loadedTypes [3]bool } // UsersOrErr returns the Users value or an error if the edge @@ -65,23 +62,10 @@ func (e TeamEdges) UsersOrErr() ([]*User, error) { return nil, &NotLoadedError{edge: "users"} } -// TeamTierOrErr returns the TeamTier value or an error if the edge -// was not loaded in eager-loading, or loaded but was not found. -func (e TeamEdges) TeamTierOrErr() (*Tier, error) { - if e.loadedTypes[1] { - if e.TeamTier == nil { - // Edge was loaded but was not found. - return nil, &NotFoundError{label: tier.Label} - } - return e.TeamTier, nil - } - return nil, &NotLoadedError{edge: "team_tier"} -} - // EnvsOrErr returns the Envs value or an error if the edge // was not loaded in eager-loading. func (e TeamEdges) EnvsOrErr() ([]*Env, error) { - if e.loadedTypes[2] { + if e.loadedTypes[1] { return e.Envs, nil } return nil, &NotLoadedError{edge: "envs"} @@ -90,7 +74,7 @@ func (e TeamEdges) EnvsOrErr() ([]*Env, error) { // UsersTeamsOrErr returns the UsersTeams value or an error if the edge // was not loaded in eager-loading. func (e TeamEdges) UsersTeamsOrErr() ([]*UsersTeams, error) { - if e.loadedTypes[3] { + if e.loadedTypes[2] { return e.UsersTeams, nil } return nil, &NotLoadedError{edge: "users_teams"} @@ -200,11 +184,6 @@ func (t *Team) QueryUsers() *UserQuery { return NewTeamClient(t.config).QueryUsers(t) } -// QueryTeamTier queries the "team_tier" edge of the Team entity. -func (t *Team) QueryTeamTier() *TierQuery { - return NewTeamClient(t.config).QueryTeamTier(t) -} - // QueryEnvs queries the "envs" edge of the Team entity. func (t *Team) QueryEnvs() *EnvQuery { return NewTeamClient(t.config).QueryEnvs(t) diff --git a/packages/shared/pkg/models/team/team.go b/packages/shared/pkg/models/team/team.go index eddc6a934e..9c20c4ef93 100644 --- a/packages/shared/pkg/models/team/team.go +++ b/packages/shared/pkg/models/team/team.go @@ -32,8 +32,6 @@ const ( FieldClusterID = "cluster_id" // EdgeUsers holds the string denoting the users edge name in mutations. EdgeUsers = "users" - // EdgeTeamTier holds the string denoting the team_tier edge name in mutations. - EdgeTeamTier = "team_tier" // EdgeEnvs holds the string denoting the envs edge name in mutations. EdgeEnvs = "envs" // EdgeUsersTeams holds the string denoting the users_teams edge name in mutations. @@ -45,13 +43,6 @@ const ( // UsersInverseTable is the table name for the User entity. // It exists in this package in order to avoid circular dependency with the "user" package. UsersInverseTable = "users" - // TeamTierTable is the table that holds the team_tier relation/edge. - TeamTierTable = "teams" - // TeamTierInverseTable is the table name for the Tier entity. - // It exists in this package in order to avoid circular dependency with the "tier" package. - TeamTierInverseTable = "tiers" - // TeamTierColumn is the table column denoting the team_tier relation/edge. - TeamTierColumn = "tier" // EnvsTable is the table that holds the envs relation/edge. EnvsTable = "envs" // EnvsInverseTable is the table name for the Env entity. @@ -166,13 +157,6 @@ func ByUsers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { } } -// ByTeamTierField orders the results by team_tier field. -func ByTeamTierField(field string, opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newTeamTierStep(), sql.OrderByField(field, opts...)) - } -} - // ByEnvsCount orders the results by envs count. func ByEnvsCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -207,13 +191,6 @@ func newUsersStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.M2M, false, UsersTable, UsersPrimaryKey...), ) } -func newTeamTierStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(TeamTierInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, TeamTierTable, TeamTierColumn), - ) -} func newEnvsStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), diff --git a/packages/shared/pkg/models/team/where.go b/packages/shared/pkg/models/team/where.go index e1b4052504..6bade1aa4d 100644 --- a/packages/shared/pkg/models/team/where.go +++ b/packages/shared/pkg/models/team/where.go @@ -526,35 +526,6 @@ func HasUsersWith(preds ...predicate.User) predicate.Team { }) } -// HasTeamTier applies the HasEdge predicate on the "team_tier" edge. -func HasTeamTier() predicate.Team { - return predicate.Team(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, TeamTierTable, TeamTierColumn), - ) - schemaConfig := internal.SchemaConfigFromContext(s.Context()) - step.To.Schema = schemaConfig.Tier - step.Edge.Schema = schemaConfig.Team - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasTeamTierWith applies the HasEdge predicate on the "team_tier" edge with a given conditions (other predicates). -func HasTeamTierWith(preds ...predicate.Tier) predicate.Team { - return predicate.Team(func(s *sql.Selector) { - step := newTeamTierStep() - schemaConfig := internal.SchemaConfigFromContext(s.Context()) - step.To.Schema = schemaConfig.Tier - step.Edge.Schema = schemaConfig.Team - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - // HasEnvs applies the HasEdge predicate on the "envs" edge. func HasEnvs() predicate.Team { return predicate.Team(func(s *sql.Selector) { diff --git a/packages/shared/pkg/models/team_create.go b/packages/shared/pkg/models/team_create.go index 837705c54d..9d8d85ec25 100644 --- a/packages/shared/pkg/models/team_create.go +++ b/packages/shared/pkg/models/team_create.go @@ -14,7 +14,6 @@ import ( "entgo.io/ent/schema/field" "github.com/e2b-dev/infra/packages/shared/pkg/models/env" "github.com/e2b-dev/infra/packages/shared/pkg/models/team" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" "github.com/e2b-dev/infra/packages/shared/pkg/models/user" "github.com/e2b-dev/infra/packages/shared/pkg/models/usersteams" "github.com/google/uuid" @@ -137,17 +136,6 @@ func (tc *TeamCreate) AddUsers(u ...*User) *TeamCreate { return tc.AddUserIDs(ids...) } -// SetTeamTierID sets the "team_tier" edge to the Tier entity by ID. -func (tc *TeamCreate) SetTeamTierID(id string) *TeamCreate { - tc.mutation.SetTeamTierID(id) - return tc -} - -// SetTeamTier sets the "team_tier" edge to the Tier entity. -func (tc *TeamCreate) SetTeamTier(t *Tier) *TeamCreate { - return tc.SetTeamTierID(t.ID) -} - // AddEnvIDs adds the "envs" edge to the Env entity by IDs. func (tc *TeamCreate) AddEnvIDs(ids ...string) *TeamCreate { tc.mutation.AddEnvIDs(ids...) @@ -238,9 +226,6 @@ func (tc *TeamCreate) check() error { return &ValidationError{Name: "email", err: fmt.Errorf(`models: validator failed for field "Team.email": %w`, err)} } } - if _, ok := tc.mutation.TeamTierID(); !ok { - return &ValidationError{Name: "team_tier", err: errors.New(`models: missing required edge "Team.team_tier"`)} - } return nil } @@ -298,6 +283,10 @@ func (tc *TeamCreate) createSpec() (*Team, *sqlgraph.CreateSpec) { _spec.SetField(team.FieldName, field.TypeString, value) _node.Name = value } + if value, ok := tc.mutation.Tier(); ok { + _spec.SetField(team.FieldTier, field.TypeString, value) + _node.Tier = value + } if value, ok := tc.mutation.Email(); ok { _spec.SetField(team.FieldEmail, field.TypeString, value) _node.Email = value @@ -327,24 +316,6 @@ func (tc *TeamCreate) createSpec() (*Team, *sqlgraph.CreateSpec) { edge.Target.Fields = specE.Fields _spec.Edges = append(_spec.Edges, edge) } - if nodes := tc.mutation.TeamTierIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: team.TeamTierTable, - Columns: []string{team.TeamTierColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(tier.FieldID, field.TypeString), - }, - } - edge.Schema = tc.schemaConfig.Team - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _node.Tier = nodes[0] - _spec.Edges = append(_spec.Edges, edge) - } if nodes := tc.mutation.EnvsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/packages/shared/pkg/models/team_query.go b/packages/shared/pkg/models/team_query.go index dad9bbf36d..68cc24e43e 100644 --- a/packages/shared/pkg/models/team_query.go +++ b/packages/shared/pkg/models/team_query.go @@ -15,7 +15,6 @@ import ( "github.com/e2b-dev/infra/packages/shared/pkg/models/internal" "github.com/e2b-dev/infra/packages/shared/pkg/models/predicate" "github.com/e2b-dev/infra/packages/shared/pkg/models/team" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" "github.com/e2b-dev/infra/packages/shared/pkg/models/user" "github.com/e2b-dev/infra/packages/shared/pkg/models/usersteams" "github.com/google/uuid" @@ -29,7 +28,6 @@ type TeamQuery struct { inters []Interceptor predicates []predicate.Team withUsers *UserQuery - withTeamTier *TierQuery withEnvs *EnvQuery withUsersTeams *UsersTeamsQuery modifiers []func(*sql.Selector) @@ -94,31 +92,6 @@ func (tq *TeamQuery) QueryUsers() *UserQuery { return query } -// QueryTeamTier chains the current query on the "team_tier" edge. -func (tq *TeamQuery) QueryTeamTier() *TierQuery { - query := (&TierClient{config: tq.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := tq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := tq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(team.Table, team.FieldID, selector), - sqlgraph.To(tier.Table, tier.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, team.TeamTierTable, team.TeamTierColumn), - ) - schemaConfig := tq.schemaConfig - step.To.Schema = schemaConfig.Tier - step.Edge.Schema = schemaConfig.Team - fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) - return fromU, nil - } - return query -} - // QueryEnvs chains the current query on the "envs" edge. func (tq *TeamQuery) QueryEnvs() *EnvQuery { query := (&EnvClient{config: tq.config}).Query() @@ -362,7 +335,6 @@ func (tq *TeamQuery) Clone() *TeamQuery { inters: append([]Interceptor{}, tq.inters...), predicates: append([]predicate.Team{}, tq.predicates...), withUsers: tq.withUsers.Clone(), - withTeamTier: tq.withTeamTier.Clone(), withEnvs: tq.withEnvs.Clone(), withUsersTeams: tq.withUsersTeams.Clone(), // clone intermediate query. @@ -382,17 +354,6 @@ func (tq *TeamQuery) WithUsers(opts ...func(*UserQuery)) *TeamQuery { return tq } -// WithTeamTier tells the query-builder to eager-load the nodes that are connected to -// the "team_tier" edge. The optional arguments are used to configure the query builder of the edge. -func (tq *TeamQuery) WithTeamTier(opts ...func(*TierQuery)) *TeamQuery { - query := (&TierClient{config: tq.config}).Query() - for _, opt := range opts { - opt(query) - } - tq.withTeamTier = query - return tq -} - // WithEnvs tells the query-builder to eager-load the nodes that are connected to // the "envs" edge. The optional arguments are used to configure the query builder of the edge. func (tq *TeamQuery) WithEnvs(opts ...func(*EnvQuery)) *TeamQuery { @@ -493,9 +454,8 @@ func (tq *TeamQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Team, e var ( nodes = []*Team{} _spec = tq.querySpec() - loadedTypes = [4]bool{ + loadedTypes = [3]bool{ tq.withUsers != nil, - tq.withTeamTier != nil, tq.withEnvs != nil, tq.withUsersTeams != nil, } @@ -530,12 +490,6 @@ func (tq *TeamQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Team, e return nil, err } } - if query := tq.withTeamTier; query != nil { - if err := tq.loadTeamTier(ctx, query, nodes, nil, - func(n *Team, e *Tier) { n.Edges.TeamTier = e }); err != nil { - return nil, err - } - } if query := tq.withEnvs; query != nil { if err := tq.loadEnvs(ctx, query, nodes, func(n *Team) { n.Edges.Envs = []*Env{} }, @@ -615,35 +569,6 @@ func (tq *TeamQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*T } return nil } -func (tq *TeamQuery) loadTeamTier(ctx context.Context, query *TierQuery, nodes []*Team, init func(*Team), assign func(*Team, *Tier)) error { - ids := make([]string, 0, len(nodes)) - nodeids := make(map[string][]*Team) - for i := range nodes { - fk := nodes[i].Tier - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) - } - nodeids[fk] = append(nodeids[fk], nodes[i]) - } - if len(ids) == 0 { - return nil - } - query.Where(tier.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return fmt.Errorf(`unexpected foreign-key "tier" returned %v`, n.ID) - } - for i := range nodes { - assign(nodes[i], n) - } - } - return nil -} func (tq *TeamQuery) loadEnvs(ctx context.Context, query *EnvQuery, nodes []*Team, init func(*Team), assign func(*Team, *Env)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[uuid.UUID]*Team) @@ -735,9 +660,6 @@ func (tq *TeamQuery) querySpec() *sqlgraph.QuerySpec { _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) } } - if tq.withTeamTier != nil { - _spec.Node.AddColumnOnce(team.FieldTier) - } } if ps := tq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { diff --git a/packages/shared/pkg/models/team_update.go b/packages/shared/pkg/models/team_update.go index ea7db4cb66..d7f23c0a67 100644 --- a/packages/shared/pkg/models/team_update.go +++ b/packages/shared/pkg/models/team_update.go @@ -14,7 +14,6 @@ import ( "github.com/e2b-dev/infra/packages/shared/pkg/models/internal" "github.com/e2b-dev/infra/packages/shared/pkg/models/predicate" "github.com/e2b-dev/infra/packages/shared/pkg/models/team" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" "github.com/e2b-dev/infra/packages/shared/pkg/models/user" "github.com/e2b-dev/infra/packages/shared/pkg/models/usersteams" "github.com/google/uuid" @@ -171,17 +170,6 @@ func (tu *TeamUpdate) AddUsers(u ...*User) *TeamUpdate { return tu.AddUserIDs(ids...) } -// SetTeamTierID sets the "team_tier" edge to the Tier entity by ID. -func (tu *TeamUpdate) SetTeamTierID(id string) *TeamUpdate { - tu.mutation.SetTeamTierID(id) - return tu -} - -// SetTeamTier sets the "team_tier" edge to the Tier entity. -func (tu *TeamUpdate) SetTeamTier(t *Tier) *TeamUpdate { - return tu.SetTeamTierID(t.ID) -} - // AddEnvIDs adds the "envs" edge to the Env entity by IDs. func (tu *TeamUpdate) AddEnvIDs(ids ...string) *TeamUpdate { tu.mutation.AddEnvIDs(ids...) @@ -238,12 +226,6 @@ func (tu *TeamUpdate) RemoveUsers(u ...*User) *TeamUpdate { return tu.RemoveUserIDs(ids...) } -// ClearTeamTier clears the "team_tier" edge to the Tier entity. -func (tu *TeamUpdate) ClearTeamTier() *TeamUpdate { - tu.mutation.ClearTeamTier() - return tu -} - // ClearEnvs clears all "envs" edges to the Env entity. func (tu *TeamUpdate) ClearEnvs() *TeamUpdate { tu.mutation.ClearEnvs() @@ -320,9 +302,6 @@ func (tu *TeamUpdate) check() error { return &ValidationError{Name: "email", err: fmt.Errorf(`models: validator failed for field "Team.email": %w`, err)} } } - if _, ok := tu.mutation.TeamTierID(); tu.mutation.TeamTierCleared() && !ok { - return errors.New(`models: clearing a required unique edge "Team.team_tier"`) - } return nil } @@ -365,6 +344,9 @@ func (tu *TeamUpdate) sqlSave(ctx context.Context) (n int, err error) { if value, ok := tu.mutation.Name(); ok { _spec.SetField(team.FieldName, field.TypeString, value) } + if value, ok := tu.mutation.Tier(); ok { + _spec.SetField(team.FieldTier, field.TypeString, value) + } if value, ok := tu.mutation.Email(); ok { _spec.SetField(team.FieldEmail, field.TypeString, value) } @@ -434,37 +416,6 @@ func (tu *TeamUpdate) sqlSave(ctx context.Context) (n int, err error) { edge.Target.Fields = specE.Fields _spec.Edges.Add = append(_spec.Edges.Add, edge) } - if tu.mutation.TeamTierCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: team.TeamTierTable, - Columns: []string{team.TeamTierColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(tier.FieldID, field.TypeString), - }, - } - edge.Schema = tu.schemaConfig.Team - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := tu.mutation.TeamTierIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: team.TeamTierTable, - Columns: []string{team.TeamTierColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(tier.FieldID, field.TypeString), - }, - } - edge.Schema = tu.schemaConfig.Team - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } if tu.mutation.EnvsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -722,17 +673,6 @@ func (tuo *TeamUpdateOne) AddUsers(u ...*User) *TeamUpdateOne { return tuo.AddUserIDs(ids...) } -// SetTeamTierID sets the "team_tier" edge to the Tier entity by ID. -func (tuo *TeamUpdateOne) SetTeamTierID(id string) *TeamUpdateOne { - tuo.mutation.SetTeamTierID(id) - return tuo -} - -// SetTeamTier sets the "team_tier" edge to the Tier entity. -func (tuo *TeamUpdateOne) SetTeamTier(t *Tier) *TeamUpdateOne { - return tuo.SetTeamTierID(t.ID) -} - // AddEnvIDs adds the "envs" edge to the Env entity by IDs. func (tuo *TeamUpdateOne) AddEnvIDs(ids ...string) *TeamUpdateOne { tuo.mutation.AddEnvIDs(ids...) @@ -789,12 +729,6 @@ func (tuo *TeamUpdateOne) RemoveUsers(u ...*User) *TeamUpdateOne { return tuo.RemoveUserIDs(ids...) } -// ClearTeamTier clears the "team_tier" edge to the Tier entity. -func (tuo *TeamUpdateOne) ClearTeamTier() *TeamUpdateOne { - tuo.mutation.ClearTeamTier() - return tuo -} - // ClearEnvs clears all "envs" edges to the Env entity. func (tuo *TeamUpdateOne) ClearEnvs() *TeamUpdateOne { tuo.mutation.ClearEnvs() @@ -884,9 +818,6 @@ func (tuo *TeamUpdateOne) check() error { return &ValidationError{Name: "email", err: fmt.Errorf(`models: validator failed for field "Team.email": %w`, err)} } } - if _, ok := tuo.mutation.TeamTierID(); tuo.mutation.TeamTierCleared() && !ok { - return errors.New(`models: clearing a required unique edge "Team.team_tier"`) - } return nil } @@ -946,6 +877,9 @@ func (tuo *TeamUpdateOne) sqlSave(ctx context.Context) (_node *Team, err error) if value, ok := tuo.mutation.Name(); ok { _spec.SetField(team.FieldName, field.TypeString, value) } + if value, ok := tuo.mutation.Tier(); ok { + _spec.SetField(team.FieldTier, field.TypeString, value) + } if value, ok := tuo.mutation.Email(); ok { _spec.SetField(team.FieldEmail, field.TypeString, value) } @@ -1015,37 +949,6 @@ func (tuo *TeamUpdateOne) sqlSave(ctx context.Context) (_node *Team, err error) edge.Target.Fields = specE.Fields _spec.Edges.Add = append(_spec.Edges.Add, edge) } - if tuo.mutation.TeamTierCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: team.TeamTierTable, - Columns: []string{team.TeamTierColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(tier.FieldID, field.TypeString), - }, - } - edge.Schema = tuo.schemaConfig.Team - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := tuo.mutation.TeamTierIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: team.TeamTierTable, - Columns: []string{team.TeamTierColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(tier.FieldID, field.TypeString), - }, - } - edge.Schema = tuo.schemaConfig.Team - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } if tuo.mutation.EnvsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/packages/shared/pkg/models/tier.go b/packages/shared/pkg/models/tier.go deleted file mode 100644 index ceab57587e..0000000000 --- a/packages/shared/pkg/models/tier.go +++ /dev/null @@ -1,173 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "fmt" - "strings" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" -) - -// Tier is the model entity for the Tier schema. -type Tier struct { - config `json:"-"` - // ID of the ent. - ID string `json:"id,omitempty"` - // Name holds the value of the "name" field. - Name string `json:"name,omitempty"` - // DiskMB holds the value of the "disk_mb" field. - DiskMB int64 `json:"disk_mb,omitempty"` - // The number of instances the team can run concurrently - ConcurrentInstances int64 `json:"concurrent_instances,omitempty"` - // The number of concurrent template builds the team can run - ConcurrentTemplateBuilds int64 `json:"concurrent_template_builds,omitempty"` - // MaxLengthHours holds the value of the "max_length_hours" field. - MaxLengthHours int64 `json:"max_length_hours,omitempty"` - // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the TierQuery when eager-loading is set. - Edges TierEdges `json:"edges"` - selectValues sql.SelectValues -} - -// TierEdges holds the relations/edges for other nodes in the graph. -type TierEdges struct { - // Teams holds the value of the teams edge. - Teams []*Team `json:"teams,omitempty"` - // loadedTypes holds the information for reporting if a - // type was loaded (or requested) in eager-loading or not. - loadedTypes [1]bool -} - -// TeamsOrErr returns the Teams value or an error if the edge -// was not loaded in eager-loading. -func (e TierEdges) TeamsOrErr() ([]*Team, error) { - if e.loadedTypes[0] { - return e.Teams, nil - } - return nil, &NotLoadedError{edge: "teams"} -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*Tier) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case tier.FieldDiskMB, tier.FieldConcurrentInstances, tier.FieldConcurrentTemplateBuilds, tier.FieldMaxLengthHours: - values[i] = new(sql.NullInt64) - case tier.FieldID, tier.FieldName: - values[i] = new(sql.NullString) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the Tier fields. -func (t *Tier) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case tier.FieldID: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field id", values[i]) - } else if value.Valid { - t.ID = value.String - } - case tier.FieldName: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field name", values[i]) - } else if value.Valid { - t.Name = value.String - } - case tier.FieldDiskMB: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field disk_mb", values[i]) - } else if value.Valid { - t.DiskMB = value.Int64 - } - case tier.FieldConcurrentInstances: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field concurrent_instances", values[i]) - } else if value.Valid { - t.ConcurrentInstances = value.Int64 - } - case tier.FieldConcurrentTemplateBuilds: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field concurrent_template_builds", values[i]) - } else if value.Valid { - t.ConcurrentTemplateBuilds = value.Int64 - } - case tier.FieldMaxLengthHours: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field max_length_hours", values[i]) - } else if value.Valid { - t.MaxLengthHours = value.Int64 - } - default: - t.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the Tier. -// This includes values selected through modifiers, order, etc. -func (t *Tier) Value(name string) (ent.Value, error) { - return t.selectValues.Get(name) -} - -// QueryTeams queries the "teams" edge of the Tier entity. -func (t *Tier) QueryTeams() *TeamQuery { - return NewTierClient(t.config).QueryTeams(t) -} - -// Update returns a builder for updating this Tier. -// Note that you need to call Tier.Unwrap() before calling this method if this Tier -// was returned from a transaction, and the transaction was committed or rolled back. -func (t *Tier) Update() *TierUpdateOne { - return NewTierClient(t.config).UpdateOne(t) -} - -// Unwrap unwraps the Tier entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (t *Tier) Unwrap() *Tier { - _tx, ok := t.config.driver.(*txDriver) - if !ok { - panic("models: Tier is not a transactional entity") - } - t.config.driver = _tx.drv - return t -} - -// String implements the fmt.Stringer. -func (t *Tier) String() string { - var builder strings.Builder - builder.WriteString("Tier(") - builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) - builder.WriteString("name=") - builder.WriteString(t.Name) - builder.WriteString(", ") - builder.WriteString("disk_mb=") - builder.WriteString(fmt.Sprintf("%v", t.DiskMB)) - builder.WriteString(", ") - builder.WriteString("concurrent_instances=") - builder.WriteString(fmt.Sprintf("%v", t.ConcurrentInstances)) - builder.WriteString(", ") - builder.WriteString("concurrent_template_builds=") - builder.WriteString(fmt.Sprintf("%v", t.ConcurrentTemplateBuilds)) - builder.WriteString(", ") - builder.WriteString("max_length_hours=") - builder.WriteString(fmt.Sprintf("%v", t.MaxLengthHours)) - builder.WriteByte(')') - return builder.String() -} - -// Tiers is a parsable slice of Tier. -type Tiers []*Tier diff --git a/packages/shared/pkg/models/tier/tier.go b/packages/shared/pkg/models/tier/tier.go deleted file mode 100644 index c1318f50d3..0000000000 --- a/packages/shared/pkg/models/tier/tier.go +++ /dev/null @@ -1,110 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package tier - -import ( - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -const ( - // Label holds the string label denoting the tier type in the database. - Label = "tier" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldName holds the string denoting the name field in the database. - FieldName = "name" - // FieldDiskMB holds the string denoting the disk_mb field in the database. - FieldDiskMB = "disk_mb" - // FieldConcurrentInstances holds the string denoting the concurrent_instances field in the database. - FieldConcurrentInstances = "concurrent_instances" - // FieldConcurrentTemplateBuilds holds the string denoting the concurrent_template_builds field in the database. - FieldConcurrentTemplateBuilds = "concurrent_template_builds" - // FieldMaxLengthHours holds the string denoting the max_length_hours field in the database. - FieldMaxLengthHours = "max_length_hours" - // EdgeTeams holds the string denoting the teams edge name in mutations. - EdgeTeams = "teams" - // Table holds the table name of the tier in the database. - Table = "tiers" - // TeamsTable is the table that holds the teams relation/edge. - TeamsTable = "teams" - // TeamsInverseTable is the table name for the Team entity. - // It exists in this package in order to avoid circular dependency with the "team" package. - TeamsInverseTable = "teams" - // TeamsColumn is the table column denoting the teams relation/edge. - TeamsColumn = "tier" -) - -// Columns holds all SQL columns for tier fields. -var Columns = []string{ - FieldID, - FieldName, - FieldDiskMB, - FieldConcurrentInstances, - FieldConcurrentTemplateBuilds, - FieldMaxLengthHours, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -// OrderOption defines the ordering options for the Tier queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} - -// ByName orders the results by the name field. -func ByName(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldName, opts...).ToFunc() -} - -// ByDiskMB orders the results by the disk_mb field. -func ByDiskMB(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldDiskMB, opts...).ToFunc() -} - -// ByConcurrentInstances orders the results by the concurrent_instances field. -func ByConcurrentInstances(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldConcurrentInstances, opts...).ToFunc() -} - -// ByConcurrentTemplateBuilds orders the results by the concurrent_template_builds field. -func ByConcurrentTemplateBuilds(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldConcurrentTemplateBuilds, opts...).ToFunc() -} - -// ByMaxLengthHours orders the results by the max_length_hours field. -func ByMaxLengthHours(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldMaxLengthHours, opts...).ToFunc() -} - -// ByTeamsCount orders the results by teams count. -func ByTeamsCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newTeamsStep(), opts...) - } -} - -// ByTeams orders the results by teams terms. -func ByTeams(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newTeamsStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} -func newTeamsStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(TeamsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, TeamsTable, TeamsColumn), - ) -} diff --git a/packages/shared/pkg/models/tier/where.go b/packages/shared/pkg/models/tier/where.go deleted file mode 100644 index 43ae54a867..0000000000 --- a/packages/shared/pkg/models/tier/where.go +++ /dev/null @@ -1,359 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package tier - -import ( - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "github.com/e2b-dev/infra/packages/shared/pkg/models/internal" - "github.com/e2b-dev/infra/packages/shared/pkg/models/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id string) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id string) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id string) predicate.Tier { - return predicate.Tier(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...string) predicate.Tier { - return predicate.Tier(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...string) predicate.Tier { - return predicate.Tier(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id string) predicate.Tier { - return predicate.Tier(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id string) predicate.Tier { - return predicate.Tier(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id string) predicate.Tier { - return predicate.Tier(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id string) predicate.Tier { - return predicate.Tier(sql.FieldLTE(FieldID, id)) -} - -// IDEqualFold applies the EqualFold predicate on the ID field. -func IDEqualFold(id string) predicate.Tier { - return predicate.Tier(sql.FieldEqualFold(FieldID, id)) -} - -// IDContainsFold applies the ContainsFold predicate on the ID field. -func IDContainsFold(id string) predicate.Tier { - return predicate.Tier(sql.FieldContainsFold(FieldID, id)) -} - -// Name applies equality check predicate on the "name" field. It's identical to NameEQ. -func Name(v string) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldName, v)) -} - -// DiskMB applies equality check predicate on the "disk_mb" field. It's identical to DiskMBEQ. -func DiskMB(v int64) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldDiskMB, v)) -} - -// ConcurrentInstances applies equality check predicate on the "concurrent_instances" field. It's identical to ConcurrentInstancesEQ. -func ConcurrentInstances(v int64) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldConcurrentInstances, v)) -} - -// ConcurrentTemplateBuilds applies equality check predicate on the "concurrent_template_builds" field. It's identical to ConcurrentTemplateBuildsEQ. -func ConcurrentTemplateBuilds(v int64) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldConcurrentTemplateBuilds, v)) -} - -// MaxLengthHours applies equality check predicate on the "max_length_hours" field. It's identical to MaxLengthHoursEQ. -func MaxLengthHours(v int64) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldMaxLengthHours, v)) -} - -// NameEQ applies the EQ predicate on the "name" field. -func NameEQ(v string) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldName, v)) -} - -// NameNEQ applies the NEQ predicate on the "name" field. -func NameNEQ(v string) predicate.Tier { - return predicate.Tier(sql.FieldNEQ(FieldName, v)) -} - -// NameIn applies the In predicate on the "name" field. -func NameIn(vs ...string) predicate.Tier { - return predicate.Tier(sql.FieldIn(FieldName, vs...)) -} - -// NameNotIn applies the NotIn predicate on the "name" field. -func NameNotIn(vs ...string) predicate.Tier { - return predicate.Tier(sql.FieldNotIn(FieldName, vs...)) -} - -// NameGT applies the GT predicate on the "name" field. -func NameGT(v string) predicate.Tier { - return predicate.Tier(sql.FieldGT(FieldName, v)) -} - -// NameGTE applies the GTE predicate on the "name" field. -func NameGTE(v string) predicate.Tier { - return predicate.Tier(sql.FieldGTE(FieldName, v)) -} - -// NameLT applies the LT predicate on the "name" field. -func NameLT(v string) predicate.Tier { - return predicate.Tier(sql.FieldLT(FieldName, v)) -} - -// NameLTE applies the LTE predicate on the "name" field. -func NameLTE(v string) predicate.Tier { - return predicate.Tier(sql.FieldLTE(FieldName, v)) -} - -// NameContains applies the Contains predicate on the "name" field. -func NameContains(v string) predicate.Tier { - return predicate.Tier(sql.FieldContains(FieldName, v)) -} - -// NameHasPrefix applies the HasPrefix predicate on the "name" field. -func NameHasPrefix(v string) predicate.Tier { - return predicate.Tier(sql.FieldHasPrefix(FieldName, v)) -} - -// NameHasSuffix applies the HasSuffix predicate on the "name" field. -func NameHasSuffix(v string) predicate.Tier { - return predicate.Tier(sql.FieldHasSuffix(FieldName, v)) -} - -// NameEqualFold applies the EqualFold predicate on the "name" field. -func NameEqualFold(v string) predicate.Tier { - return predicate.Tier(sql.FieldEqualFold(FieldName, v)) -} - -// NameContainsFold applies the ContainsFold predicate on the "name" field. -func NameContainsFold(v string) predicate.Tier { - return predicate.Tier(sql.FieldContainsFold(FieldName, v)) -} - -// DiskMBEQ applies the EQ predicate on the "disk_mb" field. -func DiskMBEQ(v int64) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldDiskMB, v)) -} - -// DiskMBNEQ applies the NEQ predicate on the "disk_mb" field. -func DiskMBNEQ(v int64) predicate.Tier { - return predicate.Tier(sql.FieldNEQ(FieldDiskMB, v)) -} - -// DiskMBIn applies the In predicate on the "disk_mb" field. -func DiskMBIn(vs ...int64) predicate.Tier { - return predicate.Tier(sql.FieldIn(FieldDiskMB, vs...)) -} - -// DiskMBNotIn applies the NotIn predicate on the "disk_mb" field. -func DiskMBNotIn(vs ...int64) predicate.Tier { - return predicate.Tier(sql.FieldNotIn(FieldDiskMB, vs...)) -} - -// DiskMBGT applies the GT predicate on the "disk_mb" field. -func DiskMBGT(v int64) predicate.Tier { - return predicate.Tier(sql.FieldGT(FieldDiskMB, v)) -} - -// DiskMBGTE applies the GTE predicate on the "disk_mb" field. -func DiskMBGTE(v int64) predicate.Tier { - return predicate.Tier(sql.FieldGTE(FieldDiskMB, v)) -} - -// DiskMBLT applies the LT predicate on the "disk_mb" field. -func DiskMBLT(v int64) predicate.Tier { - return predicate.Tier(sql.FieldLT(FieldDiskMB, v)) -} - -// DiskMBLTE applies the LTE predicate on the "disk_mb" field. -func DiskMBLTE(v int64) predicate.Tier { - return predicate.Tier(sql.FieldLTE(FieldDiskMB, v)) -} - -// ConcurrentInstancesEQ applies the EQ predicate on the "concurrent_instances" field. -func ConcurrentInstancesEQ(v int64) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldConcurrentInstances, v)) -} - -// ConcurrentInstancesNEQ applies the NEQ predicate on the "concurrent_instances" field. -func ConcurrentInstancesNEQ(v int64) predicate.Tier { - return predicate.Tier(sql.FieldNEQ(FieldConcurrentInstances, v)) -} - -// ConcurrentInstancesIn applies the In predicate on the "concurrent_instances" field. -func ConcurrentInstancesIn(vs ...int64) predicate.Tier { - return predicate.Tier(sql.FieldIn(FieldConcurrentInstances, vs...)) -} - -// ConcurrentInstancesNotIn applies the NotIn predicate on the "concurrent_instances" field. -func ConcurrentInstancesNotIn(vs ...int64) predicate.Tier { - return predicate.Tier(sql.FieldNotIn(FieldConcurrentInstances, vs...)) -} - -// ConcurrentInstancesGT applies the GT predicate on the "concurrent_instances" field. -func ConcurrentInstancesGT(v int64) predicate.Tier { - return predicate.Tier(sql.FieldGT(FieldConcurrentInstances, v)) -} - -// ConcurrentInstancesGTE applies the GTE predicate on the "concurrent_instances" field. -func ConcurrentInstancesGTE(v int64) predicate.Tier { - return predicate.Tier(sql.FieldGTE(FieldConcurrentInstances, v)) -} - -// ConcurrentInstancesLT applies the LT predicate on the "concurrent_instances" field. -func ConcurrentInstancesLT(v int64) predicate.Tier { - return predicate.Tier(sql.FieldLT(FieldConcurrentInstances, v)) -} - -// ConcurrentInstancesLTE applies the LTE predicate on the "concurrent_instances" field. -func ConcurrentInstancesLTE(v int64) predicate.Tier { - return predicate.Tier(sql.FieldLTE(FieldConcurrentInstances, v)) -} - -// ConcurrentTemplateBuildsEQ applies the EQ predicate on the "concurrent_template_builds" field. -func ConcurrentTemplateBuildsEQ(v int64) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldConcurrentTemplateBuilds, v)) -} - -// ConcurrentTemplateBuildsNEQ applies the NEQ predicate on the "concurrent_template_builds" field. -func ConcurrentTemplateBuildsNEQ(v int64) predicate.Tier { - return predicate.Tier(sql.FieldNEQ(FieldConcurrentTemplateBuilds, v)) -} - -// ConcurrentTemplateBuildsIn applies the In predicate on the "concurrent_template_builds" field. -func ConcurrentTemplateBuildsIn(vs ...int64) predicate.Tier { - return predicate.Tier(sql.FieldIn(FieldConcurrentTemplateBuilds, vs...)) -} - -// ConcurrentTemplateBuildsNotIn applies the NotIn predicate on the "concurrent_template_builds" field. -func ConcurrentTemplateBuildsNotIn(vs ...int64) predicate.Tier { - return predicate.Tier(sql.FieldNotIn(FieldConcurrentTemplateBuilds, vs...)) -} - -// ConcurrentTemplateBuildsGT applies the GT predicate on the "concurrent_template_builds" field. -func ConcurrentTemplateBuildsGT(v int64) predicate.Tier { - return predicate.Tier(sql.FieldGT(FieldConcurrentTemplateBuilds, v)) -} - -// ConcurrentTemplateBuildsGTE applies the GTE predicate on the "concurrent_template_builds" field. -func ConcurrentTemplateBuildsGTE(v int64) predicate.Tier { - return predicate.Tier(sql.FieldGTE(FieldConcurrentTemplateBuilds, v)) -} - -// ConcurrentTemplateBuildsLT applies the LT predicate on the "concurrent_template_builds" field. -func ConcurrentTemplateBuildsLT(v int64) predicate.Tier { - return predicate.Tier(sql.FieldLT(FieldConcurrentTemplateBuilds, v)) -} - -// ConcurrentTemplateBuildsLTE applies the LTE predicate on the "concurrent_template_builds" field. -func ConcurrentTemplateBuildsLTE(v int64) predicate.Tier { - return predicate.Tier(sql.FieldLTE(FieldConcurrentTemplateBuilds, v)) -} - -// MaxLengthHoursEQ applies the EQ predicate on the "max_length_hours" field. -func MaxLengthHoursEQ(v int64) predicate.Tier { - return predicate.Tier(sql.FieldEQ(FieldMaxLengthHours, v)) -} - -// MaxLengthHoursNEQ applies the NEQ predicate on the "max_length_hours" field. -func MaxLengthHoursNEQ(v int64) predicate.Tier { - return predicate.Tier(sql.FieldNEQ(FieldMaxLengthHours, v)) -} - -// MaxLengthHoursIn applies the In predicate on the "max_length_hours" field. -func MaxLengthHoursIn(vs ...int64) predicate.Tier { - return predicate.Tier(sql.FieldIn(FieldMaxLengthHours, vs...)) -} - -// MaxLengthHoursNotIn applies the NotIn predicate on the "max_length_hours" field. -func MaxLengthHoursNotIn(vs ...int64) predicate.Tier { - return predicate.Tier(sql.FieldNotIn(FieldMaxLengthHours, vs...)) -} - -// MaxLengthHoursGT applies the GT predicate on the "max_length_hours" field. -func MaxLengthHoursGT(v int64) predicate.Tier { - return predicate.Tier(sql.FieldGT(FieldMaxLengthHours, v)) -} - -// MaxLengthHoursGTE applies the GTE predicate on the "max_length_hours" field. -func MaxLengthHoursGTE(v int64) predicate.Tier { - return predicate.Tier(sql.FieldGTE(FieldMaxLengthHours, v)) -} - -// MaxLengthHoursLT applies the LT predicate on the "max_length_hours" field. -func MaxLengthHoursLT(v int64) predicate.Tier { - return predicate.Tier(sql.FieldLT(FieldMaxLengthHours, v)) -} - -// MaxLengthHoursLTE applies the LTE predicate on the "max_length_hours" field. -func MaxLengthHoursLTE(v int64) predicate.Tier { - return predicate.Tier(sql.FieldLTE(FieldMaxLengthHours, v)) -} - -// HasTeams applies the HasEdge predicate on the "teams" edge. -func HasTeams() predicate.Tier { - return predicate.Tier(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, TeamsTable, TeamsColumn), - ) - schemaConfig := internal.SchemaConfigFromContext(s.Context()) - step.To.Schema = schemaConfig.Team - step.Edge.Schema = schemaConfig.Team - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasTeamsWith applies the HasEdge predicate on the "teams" edge with a given conditions (other predicates). -func HasTeamsWith(preds ...predicate.Team) predicate.Tier { - return predicate.Tier(func(s *sql.Selector) { - step := newTeamsStep() - schemaConfig := internal.SchemaConfigFromContext(s.Context()) - step.To.Schema = schemaConfig.Team - step.Edge.Schema = schemaConfig.Team - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.Tier) predicate.Tier { - return predicate.Tier(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.Tier) predicate.Tier { - return predicate.Tier(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.Tier) predicate.Tier { - return predicate.Tier(sql.NotPredicates(p)) -} diff --git a/packages/shared/pkg/models/tier_create.go b/packages/shared/pkg/models/tier_create.go deleted file mode 100644 index 7ac8cdce64..0000000000 --- a/packages/shared/pkg/models/tier_create.go +++ /dev/null @@ -1,816 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/shared/pkg/models/team" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" - "github.com/google/uuid" -) - -// TierCreate is the builder for creating a Tier entity. -type TierCreate struct { - config - mutation *TierMutation - hooks []Hook - conflict []sql.ConflictOption -} - -// SetName sets the "name" field. -func (tc *TierCreate) SetName(s string) *TierCreate { - tc.mutation.SetName(s) - return tc -} - -// SetDiskMB sets the "disk_mb" field. -func (tc *TierCreate) SetDiskMB(i int64) *TierCreate { - tc.mutation.SetDiskMB(i) - return tc -} - -// SetConcurrentInstances sets the "concurrent_instances" field. -func (tc *TierCreate) SetConcurrentInstances(i int64) *TierCreate { - tc.mutation.SetConcurrentInstances(i) - return tc -} - -// SetConcurrentTemplateBuilds sets the "concurrent_template_builds" field. -func (tc *TierCreate) SetConcurrentTemplateBuilds(i int64) *TierCreate { - tc.mutation.SetConcurrentTemplateBuilds(i) - return tc -} - -// SetMaxLengthHours sets the "max_length_hours" field. -func (tc *TierCreate) SetMaxLengthHours(i int64) *TierCreate { - tc.mutation.SetMaxLengthHours(i) - return tc -} - -// SetID sets the "id" field. -func (tc *TierCreate) SetID(s string) *TierCreate { - tc.mutation.SetID(s) - return tc -} - -// AddTeamIDs adds the "teams" edge to the Team entity by IDs. -func (tc *TierCreate) AddTeamIDs(ids ...uuid.UUID) *TierCreate { - tc.mutation.AddTeamIDs(ids...) - return tc -} - -// AddTeams adds the "teams" edges to the Team entity. -func (tc *TierCreate) AddTeams(t ...*Team) *TierCreate { - ids := make([]uuid.UUID, len(t)) - for i := range t { - ids[i] = t[i].ID - } - return tc.AddTeamIDs(ids...) -} - -// Mutation returns the TierMutation object of the builder. -func (tc *TierCreate) Mutation() *TierMutation { - return tc.mutation -} - -// Save creates the Tier in the database. -func (tc *TierCreate) Save(ctx context.Context) (*Tier, error) { - return withHooks(ctx, tc.sqlSave, tc.mutation, tc.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (tc *TierCreate) SaveX(ctx context.Context) *Tier { - v, err := tc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (tc *TierCreate) Exec(ctx context.Context) error { - _, err := tc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (tc *TierCreate) ExecX(ctx context.Context) { - if err := tc.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (tc *TierCreate) check() error { - if _, ok := tc.mutation.Name(); !ok { - return &ValidationError{Name: "name", err: errors.New(`models: missing required field "Tier.name"`)} - } - if _, ok := tc.mutation.DiskMB(); !ok { - return &ValidationError{Name: "disk_mb", err: errors.New(`models: missing required field "Tier.disk_mb"`)} - } - if _, ok := tc.mutation.ConcurrentInstances(); !ok { - return &ValidationError{Name: "concurrent_instances", err: errors.New(`models: missing required field "Tier.concurrent_instances"`)} - } - if _, ok := tc.mutation.ConcurrentTemplateBuilds(); !ok { - return &ValidationError{Name: "concurrent_template_builds", err: errors.New(`models: missing required field "Tier.concurrent_template_builds"`)} - } - if _, ok := tc.mutation.MaxLengthHours(); !ok { - return &ValidationError{Name: "max_length_hours", err: errors.New(`models: missing required field "Tier.max_length_hours"`)} - } - return nil -} - -func (tc *TierCreate) sqlSave(ctx context.Context) (*Tier, error) { - if err := tc.check(); err != nil { - return nil, err - } - _node, _spec := tc.createSpec() - if err := sqlgraph.CreateNode(ctx, tc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - if _spec.ID.Value != nil { - if id, ok := _spec.ID.Value.(string); ok { - _node.ID = id - } else { - return nil, fmt.Errorf("unexpected Tier.ID type: %T", _spec.ID.Value) - } - } - tc.mutation.id = &_node.ID - tc.mutation.done = true - return _node, nil -} - -func (tc *TierCreate) createSpec() (*Tier, *sqlgraph.CreateSpec) { - var ( - _node = &Tier{config: tc.config} - _spec = sqlgraph.NewCreateSpec(tier.Table, sqlgraph.NewFieldSpec(tier.FieldID, field.TypeString)) - ) - _spec.Schema = tc.schemaConfig.Tier - _spec.OnConflict = tc.conflict - if id, ok := tc.mutation.ID(); ok { - _node.ID = id - _spec.ID.Value = id - } - if value, ok := tc.mutation.Name(); ok { - _spec.SetField(tier.FieldName, field.TypeString, value) - _node.Name = value - } - if value, ok := tc.mutation.DiskMB(); ok { - _spec.SetField(tier.FieldDiskMB, field.TypeInt64, value) - _node.DiskMB = value - } - if value, ok := tc.mutation.ConcurrentInstances(); ok { - _spec.SetField(tier.FieldConcurrentInstances, field.TypeInt64, value) - _node.ConcurrentInstances = value - } - if value, ok := tc.mutation.ConcurrentTemplateBuilds(); ok { - _spec.SetField(tier.FieldConcurrentTemplateBuilds, field.TypeInt64, value) - _node.ConcurrentTemplateBuilds = value - } - if value, ok := tc.mutation.MaxLengthHours(); ok { - _spec.SetField(tier.FieldMaxLengthHours, field.TypeInt64, value) - _node.MaxLengthHours = value - } - if nodes := tc.mutation.TeamsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: tier.TeamsTable, - Columns: []string{tier.TeamsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), - }, - } - edge.Schema = tc.schemaConfig.Team - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause -// of the `INSERT` statement. For example: -// -// client.Tier.Create(). -// SetName(v). -// OnConflict( -// // Update the row with the new values -// // the was proposed for insertion. -// sql.ResolveWithNewValues(), -// ). -// // Override some of the fields with custom -// // update values. -// Update(func(u *ent.TierUpsert) { -// SetName(v+v). -// }). -// Exec(ctx) -func (tc *TierCreate) OnConflict(opts ...sql.ConflictOption) *TierUpsertOne { - tc.conflict = opts - return &TierUpsertOne{ - create: tc, - } -} - -// OnConflictColumns calls `OnConflict` and configures the columns -// as conflict target. Using this option is equivalent to using: -// -// client.Tier.Create(). -// OnConflict(sql.ConflictColumns(columns...)). -// Exec(ctx) -func (tc *TierCreate) OnConflictColumns(columns ...string) *TierUpsertOne { - tc.conflict = append(tc.conflict, sql.ConflictColumns(columns...)) - return &TierUpsertOne{ - create: tc, - } -} - -type ( - // TierUpsertOne is the builder for "upsert"-ing - // one Tier node. - TierUpsertOne struct { - create *TierCreate - } - - // TierUpsert is the "OnConflict" setter. - TierUpsert struct { - *sql.UpdateSet - } -) - -// SetName sets the "name" field. -func (u *TierUpsert) SetName(v string) *TierUpsert { - u.Set(tier.FieldName, v) - return u -} - -// UpdateName sets the "name" field to the value that was provided on create. -func (u *TierUpsert) UpdateName() *TierUpsert { - u.SetExcluded(tier.FieldName) - return u -} - -// SetDiskMB sets the "disk_mb" field. -func (u *TierUpsert) SetDiskMB(v int64) *TierUpsert { - u.Set(tier.FieldDiskMB, v) - return u -} - -// UpdateDiskMB sets the "disk_mb" field to the value that was provided on create. -func (u *TierUpsert) UpdateDiskMB() *TierUpsert { - u.SetExcluded(tier.FieldDiskMB) - return u -} - -// AddDiskMB adds v to the "disk_mb" field. -func (u *TierUpsert) AddDiskMB(v int64) *TierUpsert { - u.Add(tier.FieldDiskMB, v) - return u -} - -// SetConcurrentInstances sets the "concurrent_instances" field. -func (u *TierUpsert) SetConcurrentInstances(v int64) *TierUpsert { - u.Set(tier.FieldConcurrentInstances, v) - return u -} - -// UpdateConcurrentInstances sets the "concurrent_instances" field to the value that was provided on create. -func (u *TierUpsert) UpdateConcurrentInstances() *TierUpsert { - u.SetExcluded(tier.FieldConcurrentInstances) - return u -} - -// AddConcurrentInstances adds v to the "concurrent_instances" field. -func (u *TierUpsert) AddConcurrentInstances(v int64) *TierUpsert { - u.Add(tier.FieldConcurrentInstances, v) - return u -} - -// SetConcurrentTemplateBuilds sets the "concurrent_template_builds" field. -func (u *TierUpsert) SetConcurrentTemplateBuilds(v int64) *TierUpsert { - u.Set(tier.FieldConcurrentTemplateBuilds, v) - return u -} - -// UpdateConcurrentTemplateBuilds sets the "concurrent_template_builds" field to the value that was provided on create. -func (u *TierUpsert) UpdateConcurrentTemplateBuilds() *TierUpsert { - u.SetExcluded(tier.FieldConcurrentTemplateBuilds) - return u -} - -// AddConcurrentTemplateBuilds adds v to the "concurrent_template_builds" field. -func (u *TierUpsert) AddConcurrentTemplateBuilds(v int64) *TierUpsert { - u.Add(tier.FieldConcurrentTemplateBuilds, v) - return u -} - -// SetMaxLengthHours sets the "max_length_hours" field. -func (u *TierUpsert) SetMaxLengthHours(v int64) *TierUpsert { - u.Set(tier.FieldMaxLengthHours, v) - return u -} - -// UpdateMaxLengthHours sets the "max_length_hours" field to the value that was provided on create. -func (u *TierUpsert) UpdateMaxLengthHours() *TierUpsert { - u.SetExcluded(tier.FieldMaxLengthHours) - return u -} - -// AddMaxLengthHours adds v to the "max_length_hours" field. -func (u *TierUpsert) AddMaxLengthHours(v int64) *TierUpsert { - u.Add(tier.FieldMaxLengthHours, v) - return u -} - -// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. -// Using this option is equivalent to using: -// -// client.Tier.Create(). -// OnConflict( -// sql.ResolveWithNewValues(), -// sql.ResolveWith(func(u *sql.UpdateSet) { -// u.SetIgnore(tier.FieldID) -// }), -// ). -// Exec(ctx) -func (u *TierUpsertOne) UpdateNewValues() *TierUpsertOne { - u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { - if _, exists := u.create.mutation.ID(); exists { - s.SetIgnore(tier.FieldID) - } - })) - return u -} - -// Ignore sets each column to itself in case of conflict. -// Using this option is equivalent to using: -// -// client.Tier.Create(). -// OnConflict(sql.ResolveWithIgnore()). -// Exec(ctx) -func (u *TierUpsertOne) Ignore() *TierUpsertOne { - u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) - return u -} - -// DoNothing configures the conflict_action to `DO NOTHING`. -// Supported only by SQLite and PostgreSQL. -func (u *TierUpsertOne) DoNothing() *TierUpsertOne { - u.create.conflict = append(u.create.conflict, sql.DoNothing()) - return u -} - -// Update allows overriding fields `UPDATE` values. See the TierCreate.OnConflict -// documentation for more info. -func (u *TierUpsertOne) Update(set func(*TierUpsert)) *TierUpsertOne { - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { - set(&TierUpsert{UpdateSet: update}) - })) - return u -} - -// SetName sets the "name" field. -func (u *TierUpsertOne) SetName(v string) *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.SetName(v) - }) -} - -// UpdateName sets the "name" field to the value that was provided on create. -func (u *TierUpsertOne) UpdateName() *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.UpdateName() - }) -} - -// SetDiskMB sets the "disk_mb" field. -func (u *TierUpsertOne) SetDiskMB(v int64) *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.SetDiskMB(v) - }) -} - -// AddDiskMB adds v to the "disk_mb" field. -func (u *TierUpsertOne) AddDiskMB(v int64) *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.AddDiskMB(v) - }) -} - -// UpdateDiskMB sets the "disk_mb" field to the value that was provided on create. -func (u *TierUpsertOne) UpdateDiskMB() *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.UpdateDiskMB() - }) -} - -// SetConcurrentInstances sets the "concurrent_instances" field. -func (u *TierUpsertOne) SetConcurrentInstances(v int64) *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.SetConcurrentInstances(v) - }) -} - -// AddConcurrentInstances adds v to the "concurrent_instances" field. -func (u *TierUpsertOne) AddConcurrentInstances(v int64) *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.AddConcurrentInstances(v) - }) -} - -// UpdateConcurrentInstances sets the "concurrent_instances" field to the value that was provided on create. -func (u *TierUpsertOne) UpdateConcurrentInstances() *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.UpdateConcurrentInstances() - }) -} - -// SetConcurrentTemplateBuilds sets the "concurrent_template_builds" field. -func (u *TierUpsertOne) SetConcurrentTemplateBuilds(v int64) *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.SetConcurrentTemplateBuilds(v) - }) -} - -// AddConcurrentTemplateBuilds adds v to the "concurrent_template_builds" field. -func (u *TierUpsertOne) AddConcurrentTemplateBuilds(v int64) *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.AddConcurrentTemplateBuilds(v) - }) -} - -// UpdateConcurrentTemplateBuilds sets the "concurrent_template_builds" field to the value that was provided on create. -func (u *TierUpsertOne) UpdateConcurrentTemplateBuilds() *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.UpdateConcurrentTemplateBuilds() - }) -} - -// SetMaxLengthHours sets the "max_length_hours" field. -func (u *TierUpsertOne) SetMaxLengthHours(v int64) *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.SetMaxLengthHours(v) - }) -} - -// AddMaxLengthHours adds v to the "max_length_hours" field. -func (u *TierUpsertOne) AddMaxLengthHours(v int64) *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.AddMaxLengthHours(v) - }) -} - -// UpdateMaxLengthHours sets the "max_length_hours" field to the value that was provided on create. -func (u *TierUpsertOne) UpdateMaxLengthHours() *TierUpsertOne { - return u.Update(func(s *TierUpsert) { - s.UpdateMaxLengthHours() - }) -} - -// Exec executes the query. -func (u *TierUpsertOne) Exec(ctx context.Context) error { - if len(u.create.conflict) == 0 { - return errors.New("models: missing options for TierCreate.OnConflict") - } - return u.create.Exec(ctx) -} - -// ExecX is like Exec, but panics if an error occurs. -func (u *TierUpsertOne) ExecX(ctx context.Context) { - if err := u.create.Exec(ctx); err != nil { - panic(err) - } -} - -// Exec executes the UPSERT query and returns the inserted/updated ID. -func (u *TierUpsertOne) ID(ctx context.Context) (id string, err error) { - if u.create.driver.Dialect() == dialect.MySQL { - // In case of "ON CONFLICT", there is no way to get back non-numeric ID - // fields from the database since MySQL does not support the RETURNING clause. - return id, errors.New("models: TierUpsertOne.ID is not supported by MySQL driver. Use TierUpsertOne.Exec instead") - } - node, err := u.create.Save(ctx) - if err != nil { - return id, err - } - return node.ID, nil -} - -// IDX is like ID, but panics if an error occurs. -func (u *TierUpsertOne) IDX(ctx context.Context) string { - id, err := u.ID(ctx) - if err != nil { - panic(err) - } - return id -} - -// TierCreateBulk is the builder for creating many Tier entities in bulk. -type TierCreateBulk struct { - config - err error - builders []*TierCreate - conflict []sql.ConflictOption -} - -// Save creates the Tier entities in the database. -func (tcb *TierCreateBulk) Save(ctx context.Context) ([]*Tier, error) { - if tcb.err != nil { - return nil, tcb.err - } - specs := make([]*sqlgraph.CreateSpec, len(tcb.builders)) - nodes := make([]*Tier, len(tcb.builders)) - mutators := make([]Mutator, len(tcb.builders)) - for i := range tcb.builders { - func(i int, root context.Context) { - builder := tcb.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*TierMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, tcb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - spec.OnConflict = tcb.conflict - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, tcb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, tcb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (tcb *TierCreateBulk) SaveX(ctx context.Context) []*Tier { - v, err := tcb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (tcb *TierCreateBulk) Exec(ctx context.Context) error { - _, err := tcb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (tcb *TierCreateBulk) ExecX(ctx context.Context) { - if err := tcb.Exec(ctx); err != nil { - panic(err) - } -} - -// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause -// of the `INSERT` statement. For example: -// -// client.Tier.CreateBulk(builders...). -// OnConflict( -// // Update the row with the new values -// // the was proposed for insertion. -// sql.ResolveWithNewValues(), -// ). -// // Override some of the fields with custom -// // update values. -// Update(func(u *ent.TierUpsert) { -// SetName(v+v). -// }). -// Exec(ctx) -func (tcb *TierCreateBulk) OnConflict(opts ...sql.ConflictOption) *TierUpsertBulk { - tcb.conflict = opts - return &TierUpsertBulk{ - create: tcb, - } -} - -// OnConflictColumns calls `OnConflict` and configures the columns -// as conflict target. Using this option is equivalent to using: -// -// client.Tier.Create(). -// OnConflict(sql.ConflictColumns(columns...)). -// Exec(ctx) -func (tcb *TierCreateBulk) OnConflictColumns(columns ...string) *TierUpsertBulk { - tcb.conflict = append(tcb.conflict, sql.ConflictColumns(columns...)) - return &TierUpsertBulk{ - create: tcb, - } -} - -// TierUpsertBulk is the builder for "upsert"-ing -// a bulk of Tier nodes. -type TierUpsertBulk struct { - create *TierCreateBulk -} - -// UpdateNewValues updates the mutable fields using the new values that -// were set on create. Using this option is equivalent to using: -// -// client.Tier.Create(). -// OnConflict( -// sql.ResolveWithNewValues(), -// sql.ResolveWith(func(u *sql.UpdateSet) { -// u.SetIgnore(tier.FieldID) -// }), -// ). -// Exec(ctx) -func (u *TierUpsertBulk) UpdateNewValues() *TierUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { - for _, b := range u.create.builders { - if _, exists := b.mutation.ID(); exists { - s.SetIgnore(tier.FieldID) - } - } - })) - return u -} - -// Ignore sets each column to itself in case of conflict. -// Using this option is equivalent to using: -// -// client.Tier.Create(). -// OnConflict(sql.ResolveWithIgnore()). -// Exec(ctx) -func (u *TierUpsertBulk) Ignore() *TierUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) - return u -} - -// DoNothing configures the conflict_action to `DO NOTHING`. -// Supported only by SQLite and PostgreSQL. -func (u *TierUpsertBulk) DoNothing() *TierUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.DoNothing()) - return u -} - -// Update allows overriding fields `UPDATE` values. See the TierCreateBulk.OnConflict -// documentation for more info. -func (u *TierUpsertBulk) Update(set func(*TierUpsert)) *TierUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { - set(&TierUpsert{UpdateSet: update}) - })) - return u -} - -// SetName sets the "name" field. -func (u *TierUpsertBulk) SetName(v string) *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.SetName(v) - }) -} - -// UpdateName sets the "name" field to the value that was provided on create. -func (u *TierUpsertBulk) UpdateName() *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.UpdateName() - }) -} - -// SetDiskMB sets the "disk_mb" field. -func (u *TierUpsertBulk) SetDiskMB(v int64) *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.SetDiskMB(v) - }) -} - -// AddDiskMB adds v to the "disk_mb" field. -func (u *TierUpsertBulk) AddDiskMB(v int64) *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.AddDiskMB(v) - }) -} - -// UpdateDiskMB sets the "disk_mb" field to the value that was provided on create. -func (u *TierUpsertBulk) UpdateDiskMB() *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.UpdateDiskMB() - }) -} - -// SetConcurrentInstances sets the "concurrent_instances" field. -func (u *TierUpsertBulk) SetConcurrentInstances(v int64) *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.SetConcurrentInstances(v) - }) -} - -// AddConcurrentInstances adds v to the "concurrent_instances" field. -func (u *TierUpsertBulk) AddConcurrentInstances(v int64) *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.AddConcurrentInstances(v) - }) -} - -// UpdateConcurrentInstances sets the "concurrent_instances" field to the value that was provided on create. -func (u *TierUpsertBulk) UpdateConcurrentInstances() *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.UpdateConcurrentInstances() - }) -} - -// SetConcurrentTemplateBuilds sets the "concurrent_template_builds" field. -func (u *TierUpsertBulk) SetConcurrentTemplateBuilds(v int64) *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.SetConcurrentTemplateBuilds(v) - }) -} - -// AddConcurrentTemplateBuilds adds v to the "concurrent_template_builds" field. -func (u *TierUpsertBulk) AddConcurrentTemplateBuilds(v int64) *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.AddConcurrentTemplateBuilds(v) - }) -} - -// UpdateConcurrentTemplateBuilds sets the "concurrent_template_builds" field to the value that was provided on create. -func (u *TierUpsertBulk) UpdateConcurrentTemplateBuilds() *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.UpdateConcurrentTemplateBuilds() - }) -} - -// SetMaxLengthHours sets the "max_length_hours" field. -func (u *TierUpsertBulk) SetMaxLengthHours(v int64) *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.SetMaxLengthHours(v) - }) -} - -// AddMaxLengthHours adds v to the "max_length_hours" field. -func (u *TierUpsertBulk) AddMaxLengthHours(v int64) *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.AddMaxLengthHours(v) - }) -} - -// UpdateMaxLengthHours sets the "max_length_hours" field to the value that was provided on create. -func (u *TierUpsertBulk) UpdateMaxLengthHours() *TierUpsertBulk { - return u.Update(func(s *TierUpsert) { - s.UpdateMaxLengthHours() - }) -} - -// Exec executes the query. -func (u *TierUpsertBulk) Exec(ctx context.Context) error { - if u.create.err != nil { - return u.create.err - } - for i, b := range u.create.builders { - if len(b.conflict) != 0 { - return fmt.Errorf("models: OnConflict was set for builder %d. Set it on the TierCreateBulk instead", i) - } - } - if len(u.create.conflict) == 0 { - return errors.New("models: missing options for TierCreateBulk.OnConflict") - } - return u.create.Exec(ctx) -} - -// ExecX is like Exec, but panics if an error occurs. -func (u *TierUpsertBulk) ExecX(ctx context.Context) { - if err := u.create.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/packages/shared/pkg/models/tier_delete.go b/packages/shared/pkg/models/tier_delete.go deleted file mode 100644 index 2d01d8a5eb..0000000000 --- a/packages/shared/pkg/models/tier_delete.go +++ /dev/null @@ -1,91 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/shared/pkg/models/internal" - "github.com/e2b-dev/infra/packages/shared/pkg/models/predicate" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" -) - -// TierDelete is the builder for deleting a Tier entity. -type TierDelete struct { - config - hooks []Hook - mutation *TierMutation -} - -// Where appends a list predicates to the TierDelete builder. -func (td *TierDelete) Where(ps ...predicate.Tier) *TierDelete { - td.mutation.Where(ps...) - return td -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (td *TierDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, td.sqlExec, td.mutation, td.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (td *TierDelete) ExecX(ctx context.Context) int { - n, err := td.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (td *TierDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(tier.Table, sqlgraph.NewFieldSpec(tier.FieldID, field.TypeString)) - _spec.Node.Schema = td.schemaConfig.Tier - ctx = internal.NewSchemaConfigContext(ctx, td.schemaConfig) - if ps := td.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, td.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - td.mutation.done = true - return affected, err -} - -// TierDeleteOne is the builder for deleting a single Tier entity. -type TierDeleteOne struct { - td *TierDelete -} - -// Where appends a list predicates to the TierDelete builder. -func (tdo *TierDeleteOne) Where(ps ...predicate.Tier) *TierDeleteOne { - tdo.td.mutation.Where(ps...) - return tdo -} - -// Exec executes the deletion query. -func (tdo *TierDeleteOne) Exec(ctx context.Context) error { - n, err := tdo.td.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{tier.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (tdo *TierDeleteOne) ExecX(ctx context.Context) { - if err := tdo.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/packages/shared/pkg/models/tier_query.go b/packages/shared/pkg/models/tier_query.go deleted file mode 100644 index 39b908e4f5..0000000000 --- a/packages/shared/pkg/models/tier_query.go +++ /dev/null @@ -1,638 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "database/sql/driver" - "fmt" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/shared/pkg/models/internal" - "github.com/e2b-dev/infra/packages/shared/pkg/models/predicate" - "github.com/e2b-dev/infra/packages/shared/pkg/models/team" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" -) - -// TierQuery is the builder for querying Tier entities. -type TierQuery struct { - config - ctx *QueryContext - order []tier.OrderOption - inters []Interceptor - predicates []predicate.Tier - withTeams *TeamQuery - modifiers []func(*sql.Selector) - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the TierQuery builder. -func (tq *TierQuery) Where(ps ...predicate.Tier) *TierQuery { - tq.predicates = append(tq.predicates, ps...) - return tq -} - -// Limit the number of records to be returned by this query. -func (tq *TierQuery) Limit(limit int) *TierQuery { - tq.ctx.Limit = &limit - return tq -} - -// Offset to start from. -func (tq *TierQuery) Offset(offset int) *TierQuery { - tq.ctx.Offset = &offset - return tq -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (tq *TierQuery) Unique(unique bool) *TierQuery { - tq.ctx.Unique = &unique - return tq -} - -// Order specifies how the records should be ordered. -func (tq *TierQuery) Order(o ...tier.OrderOption) *TierQuery { - tq.order = append(tq.order, o...) - return tq -} - -// QueryTeams chains the current query on the "teams" edge. -func (tq *TierQuery) QueryTeams() *TeamQuery { - query := (&TeamClient{config: tq.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := tq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := tq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(tier.Table, tier.FieldID, selector), - sqlgraph.To(team.Table, team.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, tier.TeamsTable, tier.TeamsColumn), - ) - schemaConfig := tq.schemaConfig - step.To.Schema = schemaConfig.Team - step.Edge.Schema = schemaConfig.Team - fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first Tier entity from the query. -// Returns a *NotFoundError when no Tier was found. -func (tq *TierQuery) First(ctx context.Context) (*Tier, error) { - nodes, err := tq.Limit(1).All(setContextOp(ctx, tq.ctx, "First")) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{tier.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (tq *TierQuery) FirstX(ctx context.Context) *Tier { - node, err := tq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first Tier ID from the query. -// Returns a *NotFoundError when no Tier ID was found. -func (tq *TierQuery) FirstID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = tq.Limit(1).IDs(setContextOp(ctx, tq.ctx, "FirstID")); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{tier.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (tq *TierQuery) FirstIDX(ctx context.Context) string { - id, err := tq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single Tier entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one Tier entity is found. -// Returns a *NotFoundError when no Tier entities are found. -func (tq *TierQuery) Only(ctx context.Context) (*Tier, error) { - nodes, err := tq.Limit(2).All(setContextOp(ctx, tq.ctx, "Only")) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{tier.Label} - default: - return nil, &NotSingularError{tier.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (tq *TierQuery) OnlyX(ctx context.Context) *Tier { - node, err := tq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only Tier ID in the query. -// Returns a *NotSingularError when more than one Tier ID is found. -// Returns a *NotFoundError when no entities are found. -func (tq *TierQuery) OnlyID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = tq.Limit(2).IDs(setContextOp(ctx, tq.ctx, "OnlyID")); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{tier.Label} - default: - err = &NotSingularError{tier.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (tq *TierQuery) OnlyIDX(ctx context.Context) string { - id, err := tq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of Tiers. -func (tq *TierQuery) All(ctx context.Context) ([]*Tier, error) { - ctx = setContextOp(ctx, tq.ctx, "All") - if err := tq.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*Tier, *TierQuery]() - return withInterceptors[[]*Tier](ctx, tq, qr, tq.inters) -} - -// AllX is like All, but panics if an error occurs. -func (tq *TierQuery) AllX(ctx context.Context) []*Tier { - nodes, err := tq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of Tier IDs. -func (tq *TierQuery) IDs(ctx context.Context) (ids []string, err error) { - if tq.ctx.Unique == nil && tq.path != nil { - tq.Unique(true) - } - ctx = setContextOp(ctx, tq.ctx, "IDs") - if err = tq.Select(tier.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (tq *TierQuery) IDsX(ctx context.Context) []string { - ids, err := tq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (tq *TierQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, tq.ctx, "Count") - if err := tq.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, tq, querierCount[*TierQuery](), tq.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (tq *TierQuery) CountX(ctx context.Context) int { - count, err := tq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (tq *TierQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, tq.ctx, "Exist") - switch _, err := tq.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("models: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (tq *TierQuery) ExistX(ctx context.Context) bool { - exist, err := tq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the TierQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (tq *TierQuery) Clone() *TierQuery { - if tq == nil { - return nil - } - return &TierQuery{ - config: tq.config, - ctx: tq.ctx.Clone(), - order: append([]tier.OrderOption{}, tq.order...), - inters: append([]Interceptor{}, tq.inters...), - predicates: append([]predicate.Tier{}, tq.predicates...), - withTeams: tq.withTeams.Clone(), - // clone intermediate query. - sql: tq.sql.Clone(), - path: tq.path, - } -} - -// WithTeams tells the query-builder to eager-load the nodes that are connected to -// the "teams" edge. The optional arguments are used to configure the query builder of the edge. -func (tq *TierQuery) WithTeams(opts ...func(*TeamQuery)) *TierQuery { - query := (&TeamClient{config: tq.config}).Query() - for _, opt := range opts { - opt(query) - } - tq.withTeams = query - return tq -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// Name string `json:"name,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.Tier.Query(). -// GroupBy(tier.FieldName). -// Aggregate(models.Count()). -// Scan(ctx, &v) -func (tq *TierQuery) GroupBy(field string, fields ...string) *TierGroupBy { - tq.ctx.Fields = append([]string{field}, fields...) - grbuild := &TierGroupBy{build: tq} - grbuild.flds = &tq.ctx.Fields - grbuild.label = tier.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// Name string `json:"name,omitempty"` -// } -// -// client.Tier.Query(). -// Select(tier.FieldName). -// Scan(ctx, &v) -func (tq *TierQuery) Select(fields ...string) *TierSelect { - tq.ctx.Fields = append(tq.ctx.Fields, fields...) - sbuild := &TierSelect{TierQuery: tq} - sbuild.label = tier.Label - sbuild.flds, sbuild.scan = &tq.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a TierSelect configured with the given aggregations. -func (tq *TierQuery) Aggregate(fns ...AggregateFunc) *TierSelect { - return tq.Select().Aggregate(fns...) -} - -func (tq *TierQuery) prepareQuery(ctx context.Context) error { - for _, inter := range tq.inters { - if inter == nil { - return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, tq); err != nil { - return err - } - } - } - for _, f := range tq.ctx.Fields { - if !tier.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} - } - } - if tq.path != nil { - prev, err := tq.path(ctx) - if err != nil { - return err - } - tq.sql = prev - } - return nil -} - -func (tq *TierQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Tier, error) { - var ( - nodes = []*Tier{} - _spec = tq.querySpec() - loadedTypes = [1]bool{ - tq.withTeams != nil, - } - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*Tier).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &Tier{config: tq.config} - nodes = append(nodes, node) - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - _spec.Node.Schema = tq.schemaConfig.Tier - ctx = internal.NewSchemaConfigContext(ctx, tq.schemaConfig) - if len(tq.modifiers) > 0 { - _spec.Modifiers = tq.modifiers - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, tq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - if query := tq.withTeams; query != nil { - if err := tq.loadTeams(ctx, query, nodes, - func(n *Tier) { n.Edges.Teams = []*Team{} }, - func(n *Tier, e *Team) { n.Edges.Teams = append(n.Edges.Teams, e) }); err != nil { - return nil, err - } - } - return nodes, nil -} - -func (tq *TierQuery) loadTeams(ctx context.Context, query *TeamQuery, nodes []*Tier, init func(*Tier), assign func(*Tier, *Team)) error { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[string]*Tier) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - if init != nil { - init(nodes[i]) - } - } - if len(query.ctx.Fields) > 0 { - query.ctx.AppendFieldOnce(team.FieldTier) - } - query.Where(predicate.Team(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(tier.TeamsColumn), fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - fk := n.Tier - node, ok := nodeids[fk] - if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "tier" returned %v for node %v`, fk, n.ID) - } - assign(node, n) - } - return nil -} - -func (tq *TierQuery) sqlCount(ctx context.Context) (int, error) { - _spec := tq.querySpec() - _spec.Node.Schema = tq.schemaConfig.Tier - ctx = internal.NewSchemaConfigContext(ctx, tq.schemaConfig) - if len(tq.modifiers) > 0 { - _spec.Modifiers = tq.modifiers - } - _spec.Node.Columns = tq.ctx.Fields - if len(tq.ctx.Fields) > 0 { - _spec.Unique = tq.ctx.Unique != nil && *tq.ctx.Unique - } - return sqlgraph.CountNodes(ctx, tq.driver, _spec) -} - -func (tq *TierQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(tier.Table, tier.Columns, sqlgraph.NewFieldSpec(tier.FieldID, field.TypeString)) - _spec.From = tq.sql - if unique := tq.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if tq.path != nil { - _spec.Unique = true - } - if fields := tq.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, tier.FieldID) - for i := range fields { - if fields[i] != tier.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := tq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := tq.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := tq.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := tq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (tq *TierQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(tq.driver.Dialect()) - t1 := builder.Table(tier.Table) - columns := tq.ctx.Fields - if len(columns) == 0 { - columns = tier.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if tq.sql != nil { - selector = tq.sql - selector.Select(selector.Columns(columns...)...) - } - if tq.ctx.Unique != nil && *tq.ctx.Unique { - selector.Distinct() - } - t1.Schema(tq.schemaConfig.Tier) - ctx = internal.NewSchemaConfigContext(ctx, tq.schemaConfig) - selector.WithContext(ctx) - for _, m := range tq.modifiers { - m(selector) - } - for _, p := range tq.predicates { - p(selector) - } - for _, p := range tq.order { - p(selector) - } - if offset := tq.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := tq.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// Modify adds a query modifier for attaching custom logic to queries. -func (tq *TierQuery) Modify(modifiers ...func(s *sql.Selector)) *TierSelect { - tq.modifiers = append(tq.modifiers, modifiers...) - return tq.Select() -} - -// TierGroupBy is the group-by builder for Tier entities. -type TierGroupBy struct { - selector - build *TierQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (tgb *TierGroupBy) Aggregate(fns ...AggregateFunc) *TierGroupBy { - tgb.fns = append(tgb.fns, fns...) - return tgb -} - -// Scan applies the selector query and scans the result into the given value. -func (tgb *TierGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, tgb.build.ctx, "GroupBy") - if err := tgb.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*TierQuery, *TierGroupBy](ctx, tgb.build, tgb, tgb.build.inters, v) -} - -func (tgb *TierGroupBy) sqlScan(ctx context.Context, root *TierQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(tgb.fns)) - for _, fn := range tgb.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*tgb.flds)+len(tgb.fns)) - for _, f := range *tgb.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*tgb.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := tgb.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// TierSelect is the builder for selecting fields of Tier entities. -type TierSelect struct { - *TierQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (ts *TierSelect) Aggregate(fns ...AggregateFunc) *TierSelect { - ts.fns = append(ts.fns, fns...) - return ts -} - -// Scan applies the selector query and scans the result into the given value. -func (ts *TierSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, ts.ctx, "Select") - if err := ts.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*TierQuery, *TierSelect](ctx, ts.TierQuery, ts, ts.inters, v) -} - -func (ts *TierSelect) sqlScan(ctx context.Context, root *TierQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(ts.fns)) - for _, fn := range ts.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*ts.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := ts.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// Modify adds a query modifier for attaching custom logic to queries. -func (ts *TierSelect) Modify(modifiers ...func(s *sql.Selector)) *TierSelect { - ts.modifiers = append(ts.modifiers, modifiers...) - return ts -} diff --git a/packages/shared/pkg/models/tier_update.go b/packages/shared/pkg/models/tier_update.go deleted file mode 100644 index 5188f87a2e..0000000000 --- a/packages/shared/pkg/models/tier_update.go +++ /dev/null @@ -1,616 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/shared/pkg/models/internal" - "github.com/e2b-dev/infra/packages/shared/pkg/models/predicate" - "github.com/e2b-dev/infra/packages/shared/pkg/models/team" - "github.com/e2b-dev/infra/packages/shared/pkg/models/tier" - "github.com/google/uuid" -) - -// TierUpdate is the builder for updating Tier entities. -type TierUpdate struct { - config - hooks []Hook - mutation *TierMutation - modifiers []func(*sql.UpdateBuilder) -} - -// Where appends a list predicates to the TierUpdate builder. -func (tu *TierUpdate) Where(ps ...predicate.Tier) *TierUpdate { - tu.mutation.Where(ps...) - return tu -} - -// SetName sets the "name" field. -func (tu *TierUpdate) SetName(s string) *TierUpdate { - tu.mutation.SetName(s) - return tu -} - -// SetNillableName sets the "name" field if the given value is not nil. -func (tu *TierUpdate) SetNillableName(s *string) *TierUpdate { - if s != nil { - tu.SetName(*s) - } - return tu -} - -// SetDiskMB sets the "disk_mb" field. -func (tu *TierUpdate) SetDiskMB(i int64) *TierUpdate { - tu.mutation.ResetDiskMB() - tu.mutation.SetDiskMB(i) - return tu -} - -// SetNillableDiskMB sets the "disk_mb" field if the given value is not nil. -func (tu *TierUpdate) SetNillableDiskMB(i *int64) *TierUpdate { - if i != nil { - tu.SetDiskMB(*i) - } - return tu -} - -// AddDiskMB adds i to the "disk_mb" field. -func (tu *TierUpdate) AddDiskMB(i int64) *TierUpdate { - tu.mutation.AddDiskMB(i) - return tu -} - -// SetConcurrentInstances sets the "concurrent_instances" field. -func (tu *TierUpdate) SetConcurrentInstances(i int64) *TierUpdate { - tu.mutation.ResetConcurrentInstances() - tu.mutation.SetConcurrentInstances(i) - return tu -} - -// SetNillableConcurrentInstances sets the "concurrent_instances" field if the given value is not nil. -func (tu *TierUpdate) SetNillableConcurrentInstances(i *int64) *TierUpdate { - if i != nil { - tu.SetConcurrentInstances(*i) - } - return tu -} - -// AddConcurrentInstances adds i to the "concurrent_instances" field. -func (tu *TierUpdate) AddConcurrentInstances(i int64) *TierUpdate { - tu.mutation.AddConcurrentInstances(i) - return tu -} - -// SetConcurrentTemplateBuilds sets the "concurrent_template_builds" field. -func (tu *TierUpdate) SetConcurrentTemplateBuilds(i int64) *TierUpdate { - tu.mutation.ResetConcurrentTemplateBuilds() - tu.mutation.SetConcurrentTemplateBuilds(i) - return tu -} - -// SetNillableConcurrentTemplateBuilds sets the "concurrent_template_builds" field if the given value is not nil. -func (tu *TierUpdate) SetNillableConcurrentTemplateBuilds(i *int64) *TierUpdate { - if i != nil { - tu.SetConcurrentTemplateBuilds(*i) - } - return tu -} - -// AddConcurrentTemplateBuilds adds i to the "concurrent_template_builds" field. -func (tu *TierUpdate) AddConcurrentTemplateBuilds(i int64) *TierUpdate { - tu.mutation.AddConcurrentTemplateBuilds(i) - return tu -} - -// SetMaxLengthHours sets the "max_length_hours" field. -func (tu *TierUpdate) SetMaxLengthHours(i int64) *TierUpdate { - tu.mutation.ResetMaxLengthHours() - tu.mutation.SetMaxLengthHours(i) - return tu -} - -// SetNillableMaxLengthHours sets the "max_length_hours" field if the given value is not nil. -func (tu *TierUpdate) SetNillableMaxLengthHours(i *int64) *TierUpdate { - if i != nil { - tu.SetMaxLengthHours(*i) - } - return tu -} - -// AddMaxLengthHours adds i to the "max_length_hours" field. -func (tu *TierUpdate) AddMaxLengthHours(i int64) *TierUpdate { - tu.mutation.AddMaxLengthHours(i) - return tu -} - -// AddTeamIDs adds the "teams" edge to the Team entity by IDs. -func (tu *TierUpdate) AddTeamIDs(ids ...uuid.UUID) *TierUpdate { - tu.mutation.AddTeamIDs(ids...) - return tu -} - -// AddTeams adds the "teams" edges to the Team entity. -func (tu *TierUpdate) AddTeams(t ...*Team) *TierUpdate { - ids := make([]uuid.UUID, len(t)) - for i := range t { - ids[i] = t[i].ID - } - return tu.AddTeamIDs(ids...) -} - -// Mutation returns the TierMutation object of the builder. -func (tu *TierUpdate) Mutation() *TierMutation { - return tu.mutation -} - -// ClearTeams clears all "teams" edges to the Team entity. -func (tu *TierUpdate) ClearTeams() *TierUpdate { - tu.mutation.ClearTeams() - return tu -} - -// RemoveTeamIDs removes the "teams" edge to Team entities by IDs. -func (tu *TierUpdate) RemoveTeamIDs(ids ...uuid.UUID) *TierUpdate { - tu.mutation.RemoveTeamIDs(ids...) - return tu -} - -// RemoveTeams removes "teams" edges to Team entities. -func (tu *TierUpdate) RemoveTeams(t ...*Team) *TierUpdate { - ids := make([]uuid.UUID, len(t)) - for i := range t { - ids[i] = t[i].ID - } - return tu.RemoveTeamIDs(ids...) -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (tu *TierUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, tu.sqlSave, tu.mutation, tu.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (tu *TierUpdate) SaveX(ctx context.Context) int { - affected, err := tu.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (tu *TierUpdate) Exec(ctx context.Context) error { - _, err := tu.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (tu *TierUpdate) ExecX(ctx context.Context) { - if err := tu.Exec(ctx); err != nil { - panic(err) - } -} - -// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. -func (tu *TierUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TierUpdate { - tu.modifiers = append(tu.modifiers, modifiers...) - return tu -} - -func (tu *TierUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := sqlgraph.NewUpdateSpec(tier.Table, tier.Columns, sqlgraph.NewFieldSpec(tier.FieldID, field.TypeString)) - if ps := tu.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := tu.mutation.Name(); ok { - _spec.SetField(tier.FieldName, field.TypeString, value) - } - if value, ok := tu.mutation.DiskMB(); ok { - _spec.SetField(tier.FieldDiskMB, field.TypeInt64, value) - } - if value, ok := tu.mutation.AddedDiskMB(); ok { - _spec.AddField(tier.FieldDiskMB, field.TypeInt64, value) - } - if value, ok := tu.mutation.ConcurrentInstances(); ok { - _spec.SetField(tier.FieldConcurrentInstances, field.TypeInt64, value) - } - if value, ok := tu.mutation.AddedConcurrentInstances(); ok { - _spec.AddField(tier.FieldConcurrentInstances, field.TypeInt64, value) - } - if value, ok := tu.mutation.ConcurrentTemplateBuilds(); ok { - _spec.SetField(tier.FieldConcurrentTemplateBuilds, field.TypeInt64, value) - } - if value, ok := tu.mutation.AddedConcurrentTemplateBuilds(); ok { - _spec.AddField(tier.FieldConcurrentTemplateBuilds, field.TypeInt64, value) - } - if value, ok := tu.mutation.MaxLengthHours(); ok { - _spec.SetField(tier.FieldMaxLengthHours, field.TypeInt64, value) - } - if value, ok := tu.mutation.AddedMaxLengthHours(); ok { - _spec.AddField(tier.FieldMaxLengthHours, field.TypeInt64, value) - } - if tu.mutation.TeamsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: tier.TeamsTable, - Columns: []string{tier.TeamsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), - }, - } - edge.Schema = tu.schemaConfig.Team - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := tu.mutation.RemovedTeamsIDs(); len(nodes) > 0 && !tu.mutation.TeamsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: tier.TeamsTable, - Columns: []string{tier.TeamsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), - }, - } - edge.Schema = tu.schemaConfig.Team - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := tu.mutation.TeamsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: tier.TeamsTable, - Columns: []string{tier.TeamsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), - }, - } - edge.Schema = tu.schemaConfig.Team - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _spec.Node.Schema = tu.schemaConfig.Tier - ctx = internal.NewSchemaConfigContext(ctx, tu.schemaConfig) - _spec.AddModifiers(tu.modifiers...) - if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{tier.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - tu.mutation.done = true - return n, nil -} - -// TierUpdateOne is the builder for updating a single Tier entity. -type TierUpdateOne struct { - config - fields []string - hooks []Hook - mutation *TierMutation - modifiers []func(*sql.UpdateBuilder) -} - -// SetName sets the "name" field. -func (tuo *TierUpdateOne) SetName(s string) *TierUpdateOne { - tuo.mutation.SetName(s) - return tuo -} - -// SetNillableName sets the "name" field if the given value is not nil. -func (tuo *TierUpdateOne) SetNillableName(s *string) *TierUpdateOne { - if s != nil { - tuo.SetName(*s) - } - return tuo -} - -// SetDiskMB sets the "disk_mb" field. -func (tuo *TierUpdateOne) SetDiskMB(i int64) *TierUpdateOne { - tuo.mutation.ResetDiskMB() - tuo.mutation.SetDiskMB(i) - return tuo -} - -// SetNillableDiskMB sets the "disk_mb" field if the given value is not nil. -func (tuo *TierUpdateOne) SetNillableDiskMB(i *int64) *TierUpdateOne { - if i != nil { - tuo.SetDiskMB(*i) - } - return tuo -} - -// AddDiskMB adds i to the "disk_mb" field. -func (tuo *TierUpdateOne) AddDiskMB(i int64) *TierUpdateOne { - tuo.mutation.AddDiskMB(i) - return tuo -} - -// SetConcurrentInstances sets the "concurrent_instances" field. -func (tuo *TierUpdateOne) SetConcurrentInstances(i int64) *TierUpdateOne { - tuo.mutation.ResetConcurrentInstances() - tuo.mutation.SetConcurrentInstances(i) - return tuo -} - -// SetNillableConcurrentInstances sets the "concurrent_instances" field if the given value is not nil. -func (tuo *TierUpdateOne) SetNillableConcurrentInstances(i *int64) *TierUpdateOne { - if i != nil { - tuo.SetConcurrentInstances(*i) - } - return tuo -} - -// AddConcurrentInstances adds i to the "concurrent_instances" field. -func (tuo *TierUpdateOne) AddConcurrentInstances(i int64) *TierUpdateOne { - tuo.mutation.AddConcurrentInstances(i) - return tuo -} - -// SetConcurrentTemplateBuilds sets the "concurrent_template_builds" field. -func (tuo *TierUpdateOne) SetConcurrentTemplateBuilds(i int64) *TierUpdateOne { - tuo.mutation.ResetConcurrentTemplateBuilds() - tuo.mutation.SetConcurrentTemplateBuilds(i) - return tuo -} - -// SetNillableConcurrentTemplateBuilds sets the "concurrent_template_builds" field if the given value is not nil. -func (tuo *TierUpdateOne) SetNillableConcurrentTemplateBuilds(i *int64) *TierUpdateOne { - if i != nil { - tuo.SetConcurrentTemplateBuilds(*i) - } - return tuo -} - -// AddConcurrentTemplateBuilds adds i to the "concurrent_template_builds" field. -func (tuo *TierUpdateOne) AddConcurrentTemplateBuilds(i int64) *TierUpdateOne { - tuo.mutation.AddConcurrentTemplateBuilds(i) - return tuo -} - -// SetMaxLengthHours sets the "max_length_hours" field. -func (tuo *TierUpdateOne) SetMaxLengthHours(i int64) *TierUpdateOne { - tuo.mutation.ResetMaxLengthHours() - tuo.mutation.SetMaxLengthHours(i) - return tuo -} - -// SetNillableMaxLengthHours sets the "max_length_hours" field if the given value is not nil. -func (tuo *TierUpdateOne) SetNillableMaxLengthHours(i *int64) *TierUpdateOne { - if i != nil { - tuo.SetMaxLengthHours(*i) - } - return tuo -} - -// AddMaxLengthHours adds i to the "max_length_hours" field. -func (tuo *TierUpdateOne) AddMaxLengthHours(i int64) *TierUpdateOne { - tuo.mutation.AddMaxLengthHours(i) - return tuo -} - -// AddTeamIDs adds the "teams" edge to the Team entity by IDs. -func (tuo *TierUpdateOne) AddTeamIDs(ids ...uuid.UUID) *TierUpdateOne { - tuo.mutation.AddTeamIDs(ids...) - return tuo -} - -// AddTeams adds the "teams" edges to the Team entity. -func (tuo *TierUpdateOne) AddTeams(t ...*Team) *TierUpdateOne { - ids := make([]uuid.UUID, len(t)) - for i := range t { - ids[i] = t[i].ID - } - return tuo.AddTeamIDs(ids...) -} - -// Mutation returns the TierMutation object of the builder. -func (tuo *TierUpdateOne) Mutation() *TierMutation { - return tuo.mutation -} - -// ClearTeams clears all "teams" edges to the Team entity. -func (tuo *TierUpdateOne) ClearTeams() *TierUpdateOne { - tuo.mutation.ClearTeams() - return tuo -} - -// RemoveTeamIDs removes the "teams" edge to Team entities by IDs. -func (tuo *TierUpdateOne) RemoveTeamIDs(ids ...uuid.UUID) *TierUpdateOne { - tuo.mutation.RemoveTeamIDs(ids...) - return tuo -} - -// RemoveTeams removes "teams" edges to Team entities. -func (tuo *TierUpdateOne) RemoveTeams(t ...*Team) *TierUpdateOne { - ids := make([]uuid.UUID, len(t)) - for i := range t { - ids[i] = t[i].ID - } - return tuo.RemoveTeamIDs(ids...) -} - -// Where appends a list predicates to the TierUpdate builder. -func (tuo *TierUpdateOne) Where(ps ...predicate.Tier) *TierUpdateOne { - tuo.mutation.Where(ps...) - return tuo -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (tuo *TierUpdateOne) Select(field string, fields ...string) *TierUpdateOne { - tuo.fields = append([]string{field}, fields...) - return tuo -} - -// Save executes the query and returns the updated Tier entity. -func (tuo *TierUpdateOne) Save(ctx context.Context) (*Tier, error) { - return withHooks(ctx, tuo.sqlSave, tuo.mutation, tuo.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (tuo *TierUpdateOne) SaveX(ctx context.Context) *Tier { - node, err := tuo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (tuo *TierUpdateOne) Exec(ctx context.Context) error { - _, err := tuo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (tuo *TierUpdateOne) ExecX(ctx context.Context) { - if err := tuo.Exec(ctx); err != nil { - panic(err) - } -} - -// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. -func (tuo *TierUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TierUpdateOne { - tuo.modifiers = append(tuo.modifiers, modifiers...) - return tuo -} - -func (tuo *TierUpdateOne) sqlSave(ctx context.Context) (_node *Tier, err error) { - _spec := sqlgraph.NewUpdateSpec(tier.Table, tier.Columns, sqlgraph.NewFieldSpec(tier.FieldID, field.TypeString)) - id, ok := tuo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Tier.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := tuo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, tier.FieldID) - for _, f := range fields { - if !tier.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} - } - if f != tier.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := tuo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := tuo.mutation.Name(); ok { - _spec.SetField(tier.FieldName, field.TypeString, value) - } - if value, ok := tuo.mutation.DiskMB(); ok { - _spec.SetField(tier.FieldDiskMB, field.TypeInt64, value) - } - if value, ok := tuo.mutation.AddedDiskMB(); ok { - _spec.AddField(tier.FieldDiskMB, field.TypeInt64, value) - } - if value, ok := tuo.mutation.ConcurrentInstances(); ok { - _spec.SetField(tier.FieldConcurrentInstances, field.TypeInt64, value) - } - if value, ok := tuo.mutation.AddedConcurrentInstances(); ok { - _spec.AddField(tier.FieldConcurrentInstances, field.TypeInt64, value) - } - if value, ok := tuo.mutation.ConcurrentTemplateBuilds(); ok { - _spec.SetField(tier.FieldConcurrentTemplateBuilds, field.TypeInt64, value) - } - if value, ok := tuo.mutation.AddedConcurrentTemplateBuilds(); ok { - _spec.AddField(tier.FieldConcurrentTemplateBuilds, field.TypeInt64, value) - } - if value, ok := tuo.mutation.MaxLengthHours(); ok { - _spec.SetField(tier.FieldMaxLengthHours, field.TypeInt64, value) - } - if value, ok := tuo.mutation.AddedMaxLengthHours(); ok { - _spec.AddField(tier.FieldMaxLengthHours, field.TypeInt64, value) - } - if tuo.mutation.TeamsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: tier.TeamsTable, - Columns: []string{tier.TeamsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), - }, - } - edge.Schema = tuo.schemaConfig.Team - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := tuo.mutation.RemovedTeamsIDs(); len(nodes) > 0 && !tuo.mutation.TeamsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: tier.TeamsTable, - Columns: []string{tier.TeamsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), - }, - } - edge.Schema = tuo.schemaConfig.Team - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := tuo.mutation.TeamsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: tier.TeamsTable, - Columns: []string{tier.TeamsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), - }, - } - edge.Schema = tuo.schemaConfig.Team - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _spec.Node.Schema = tuo.schemaConfig.Tier - ctx = internal.NewSchemaConfigContext(ctx, tuo.schemaConfig) - _spec.AddModifiers(tuo.modifiers...) - _node = &Tier{config: tuo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{tier.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - tuo.mutation.done = true - return _node, nil -} diff --git a/packages/shared/pkg/models/tx.go b/packages/shared/pkg/models/tx.go index 7a1d68023f..5d26d0514f 100644 --- a/packages/shared/pkg/models/tx.go +++ b/packages/shared/pkg/models/tx.go @@ -26,8 +26,6 @@ type Tx struct { Snapshot *SnapshotClient // Team is the client for interacting with the Team builders. Team *TeamClient - // Tier is the client for interacting with the Tier builders. - Tier *TierClient // User is the client for interacting with the User builders. User *UserClient // UsersTeams is the client for interacting with the UsersTeams builders. @@ -170,7 +168,6 @@ func (tx *Tx) init() { tx.EnvBuild = NewEnvBuildClient(tx.config) tx.Snapshot = NewSnapshotClient(tx.config) tx.Team = NewTeamClient(tx.config) - tx.Tier = NewTierClient(tx.config) tx.User = NewUserClient(tx.config) tx.UsersTeams = NewUsersTeamsClient(tx.config) } diff --git a/packages/shared/pkg/schema/team.go b/packages/shared/pkg/schema/team.go index 424b7702a7..6f37af4027 100644 --- a/packages/shared/pkg/schema/team.go +++ b/packages/shared/pkg/schema/team.go @@ -34,7 +34,6 @@ func (Team) Fields() []ent.Field { func (Team) Edges() []ent.Edge { return []ent.Edge{ edge.To("users", User.Type).Through("users_teams", UsersTeams.Type).Annotations(entsql.OnDelete(entsql.Cascade)), - edge.From("team_tier", Tier.Type).Ref("teams").Unique().Field("tier").Required(), edge.To("envs", Env.Type), } } diff --git a/packages/shared/pkg/schema/tier.go b/packages/shared/pkg/schema/tier.go deleted file mode 100644 index f05d044dc5..0000000000 --- a/packages/shared/pkg/schema/tier.go +++ /dev/null @@ -1,51 +0,0 @@ -package schema - -import ( - "entgo.io/ent" - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/entsql" - "entgo.io/ent/schema" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" -) - -type Tier struct { - ent.Schema -} - -func (Tier) Fields() []ent.Field { - return []ent.Field{ - field.String("id").Immutable().Unique().SchemaType(map[string]string{dialect.Postgres: "text"}), - field.String("name").SchemaType(map[string]string{dialect.Postgres: "text"}), - field.Int64("disk_mb").Annotations(entsql.Check("disk_mb > 0"), entsql.Default("512")), - field.Int64("concurrent_instances").Annotations(entsql.Check("concurrent_instances > 0")).Comment("The number of instances the team can run concurrently"), - field.Int64("concurrent_template_builds").Annotations(entsql.Check("concurrent_template_builds > 0")).Comment("The number of concurrent template builds the team can run"), - field.Int64("max_length_hours"), - } -} - -func (Tier) Annotations() []schema.Annotation { - withComments := true - return []schema.Annotation{ - entsql.Annotation{ - WithComments: &withComments, - Checks: map[string]string{ - "tiers_concurrent_sessions_check": "concurrent_instances > 0", - "tiers_concurrent_template_builds_check": "concurrent_template_builds > 0", - "tiers_disk_mb_check": "disk_mb > 0", - }, - }, - } -} - -func (Tier) Edges() []ent.Edge { - return []ent.Edge{ - edge.To("teams", Team.Type), - } -} - -func (Tier) Mixin() []ent.Mixin { - return []ent.Mixin{ - Mixin{}, - } -}