diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index e148c5c363e7..a7eb3cd782cc 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -96,9 +96,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { usageLogRepository := repository.NewUsageLogRepository(client, db) usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator) opsRepository := repository.NewOpsRepository(db) - batchImageRepository := repository.NewBatchImageRepository(db) - batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig) - batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig) usageBillingRepository := repository.NewUsageBillingRepository(client, db) gatewayCache := repository.NewGatewayCache(redisClient) schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db) @@ -137,11 +134,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { channelRepository := repository.NewChannelRepository(db) channelService := service.NewChannelService(channelRepository, groupRepository, apiKeyAuthCacheInvalidator, pricingService) modelPricingResolver := service.NewModelPricingResolver(channelService, billingService) - batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver) - batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig) - batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig) - batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig) - batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig) notificationEmailService := service.NewNotificationEmailService(settingRepository, emailService) balanceNotifyService := service.ProvideBalanceNotifyService(emailService, settingRepository, accountRepository, notificationEmailService) gatewayService := service.NewGatewayService(accountRepository, groupRepository, usageLogRepository, usageBillingRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, identityService, httpUpstream, deferredService, claudeTokenProvider, sessionLimitCache, rpmCache, digestSessionStore, settingService, tlsFingerprintProfileService, channelService, modelPricingResolver, balanceNotifyService, serviceUserPlatformQuotaRepository) @@ -249,6 +241,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { channelMonitorRequestTemplateRepository := repository.NewChannelMonitorRequestTemplateRepository(client, db) channelMonitorRequestTemplateService := service.NewChannelMonitorRequestTemplateService(channelMonitorRequestTemplateRepository) channelMonitorRequestTemplateHandler := admin.NewChannelMonitorRequestTemplateHandler(channelMonitorRequestTemplateService) + schedulingPolicyRepository := repository.NewSchedulingPolicyRepository(client) + schedulingPolicyService := service.ProvideSchedulingPolicyService(schedulingPolicyRepository, accountRepository, channelMonitorService) + schedulingPolicyHandler := admin.NewSchedulingPolicyHandler(schedulingPolicyService) contentModerationRepository := repository.NewContentModerationRepository(db) contentModerationHashCache := repository.NewContentModerationHashCache(redisClient) contentModerationService := service.NewContentModerationService(settingRepository, contentModerationRepository, contentModerationHashCache, groupRepository, userRepository, apiKeyAuthCacheInvalidator, emailService) @@ -256,7 +251,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { paymentHandler := admin.NewPaymentHandler(paymentService, paymentConfigService) affiliateHandler := admin.NewAffiliateHandler(affiliateService, adminService) complianceHandler := admin.NewComplianceHandler(settingService) - adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, backupHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, grokOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, tlsFingerprintProfileHandler, adminAPIKeyHandler, scheduledTestHandler, channelHandler, channelMonitorHandler, channelMonitorRequestTemplateHandler, contentModerationHandler, paymentHandler, affiliateHandler, complianceHandler) + adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, backupHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, grokOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, tlsFingerprintProfileHandler, adminAPIKeyHandler, scheduledTestHandler, channelHandler, channelMonitorHandler, channelMonitorRequestTemplateHandler, schedulingPolicyHandler, contentModerationHandler, paymentHandler, affiliateHandler, complianceHandler) usageRecordWorkerPool := service.NewUsageRecordWorkerPool(configConfig) userMsgQueueCache := repository.NewUserMsgQueueCache(redisClient) userMessageQueueService := service.ProvideUserMessageQueueService(userMsgQueueCache, rpmCache, configConfig) @@ -267,6 +262,13 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { handlerPaymentHandler := handler.NewPaymentHandler(paymentService, paymentConfigService, channelService) paymentWebhookHandler := handler.NewPaymentWebhookHandler(paymentService, registry) availableChannelHandler := handler.NewAvailableChannelHandler(channelService, apiKeyService, settingService) + batchImageRepository := repository.NewBatchImageRepository(db) + batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig) + batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver) + batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig) + batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig) + batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig) + batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig) batchImageHandler := handler.NewBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService) idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig) idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig) @@ -285,6 +287,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { accountExpiryService := service.ProvideAccountExpiryService(accountRepository) proxyExpiryService := service.ProvideProxyExpiryService(proxyRepository) subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository, settingRepository, notificationEmailService, leaderLockCache, db) + batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig) scheduledTestRunnerService := service.ProvideScheduledTestRunnerService(scheduledTestPlanRepository, scheduledTestService, accountTestService, rateLimitService, configConfig) paymentOrderExpiryService := service.ProvidePaymentOrderExpiryService(paymentService, leaderLockCache, db) channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService) diff --git a/backend/ent/client.go b/backend/ent/client.go index e9b74fcfeffd..3acf70366f58 100644 --- a/backend/ent/client.go +++ b/backend/ent/client.go @@ -41,6 +41,8 @@ import ( "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/subscriptionplan" @@ -114,6 +116,10 @@ type Client struct { Proxy *ProxyClient // RedeemCode is the client for interacting with the RedeemCode builders. RedeemCode *RedeemCodeClient + // SchedulingAction is the client for interacting with the SchedulingAction builders. + SchedulingAction *SchedulingActionClient + // SchedulingPolicy is the client for interacting with the SchedulingPolicy builders. + SchedulingPolicy *SchedulingPolicyClient // SecuritySecret is the client for interacting with the SecuritySecret builders. SecuritySecret *SecuritySecretClient // Setting is the client for interacting with the Setting builders. @@ -175,6 +181,8 @@ func (c *Client) init() { c.PromoCodeUsage = NewPromoCodeUsageClient(c.config) c.Proxy = NewProxyClient(c.config) c.RedeemCode = NewRedeemCodeClient(c.config) + c.SchedulingAction = NewSchedulingActionClient(c.config) + c.SchedulingPolicy = NewSchedulingPolicyClient(c.config) c.SecuritySecret = NewSecuritySecretClient(c.config) c.Setting = NewSettingClient(c.config) c.SubscriptionPlan = NewSubscriptionPlanClient(c.config) @@ -305,6 +313,8 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { PromoCodeUsage: NewPromoCodeUsageClient(cfg), Proxy: NewProxyClient(cfg), RedeemCode: NewRedeemCodeClient(cfg), + SchedulingAction: NewSchedulingActionClient(cfg), + SchedulingPolicy: NewSchedulingPolicyClient(cfg), SecuritySecret: NewSecuritySecretClient(cfg), Setting: NewSettingClient(cfg), SubscriptionPlan: NewSubscriptionPlanClient(cfg), @@ -362,6 +372,8 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) PromoCodeUsage: NewPromoCodeUsageClient(cfg), Proxy: NewProxyClient(cfg), RedeemCode: NewRedeemCodeClient(cfg), + SchedulingAction: NewSchedulingActionClient(cfg), + SchedulingPolicy: NewSchedulingPolicyClient(cfg), SecuritySecret: NewSecuritySecretClient(cfg), Setting: NewSettingClient(cfg), SubscriptionPlan: NewSubscriptionPlanClient(cfg), @@ -410,10 +422,11 @@ func (c *Client) Use(hooks ...Hook) { c.ErrorPassthroughRule, c.Group, c.IdempotencyRecord, c.IdentityAdoptionDecision, c.PaymentAuditLog, c.PaymentOrder, c.PaymentProviderInstance, c.PendingAuthSession, c.PromoCode, c.PromoCodeUsage, - c.Proxy, c.RedeemCode, c.SecuritySecret, c.Setting, c.SubscriptionPlan, - c.TLSFingerprintProfile, c.UsageCleanupTask, c.UsageLog, c.User, - c.UserAllowedGroup, c.UserAttributeDefinition, c.UserAttributeValue, - c.UserPlatformQuota, c.UserSubscription, + c.Proxy, c.RedeemCode, c.SchedulingAction, c.SchedulingPolicy, + c.SecuritySecret, c.Setting, c.SubscriptionPlan, c.TLSFingerprintProfile, + c.UsageCleanupTask, c.UsageLog, c.User, c.UserAllowedGroup, + c.UserAttributeDefinition, c.UserAttributeValue, c.UserPlatformQuota, + c.UserSubscription, } { n.Use(hooks...) } @@ -430,10 +443,11 @@ func (c *Client) Intercept(interceptors ...Interceptor) { c.ErrorPassthroughRule, c.Group, c.IdempotencyRecord, c.IdentityAdoptionDecision, c.PaymentAuditLog, c.PaymentOrder, c.PaymentProviderInstance, c.PendingAuthSession, c.PromoCode, c.PromoCodeUsage, - c.Proxy, c.RedeemCode, c.SecuritySecret, c.Setting, c.SubscriptionPlan, - c.TLSFingerprintProfile, c.UsageCleanupTask, c.UsageLog, c.User, - c.UserAllowedGroup, c.UserAttributeDefinition, c.UserAttributeValue, - c.UserPlatformQuota, c.UserSubscription, + c.Proxy, c.RedeemCode, c.SchedulingAction, c.SchedulingPolicy, + c.SecuritySecret, c.Setting, c.SubscriptionPlan, c.TLSFingerprintProfile, + c.UsageCleanupTask, c.UsageLog, c.User, c.UserAllowedGroup, + c.UserAttributeDefinition, c.UserAttributeValue, c.UserPlatformQuota, + c.UserSubscription, } { n.Intercept(interceptors...) } @@ -494,6 +508,10 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.Proxy.mutate(ctx, m) case *RedeemCodeMutation: return c.RedeemCode.mutate(ctx, m) + case *SchedulingActionMutation: + return c.SchedulingAction.mutate(ctx, m) + case *SchedulingPolicyMutation: + return c.SchedulingPolicy.mutate(ctx, m) case *SecuritySecretMutation: return c.SecuritySecret.mutate(ctx, m) case *SettingMutation: @@ -4644,6 +4662,272 @@ func (c *RedeemCodeClient) mutate(ctx context.Context, m *RedeemCodeMutation) (V } } +// SchedulingActionClient is a client for the SchedulingAction schema. +type SchedulingActionClient struct { + config +} + +// NewSchedulingActionClient returns a client for the SchedulingAction from the given config. +func NewSchedulingActionClient(c config) *SchedulingActionClient { + return &SchedulingActionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `schedulingaction.Hooks(f(g(h())))`. +func (c *SchedulingActionClient) Use(hooks ...Hook) { + c.hooks.SchedulingAction = append(c.hooks.SchedulingAction, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `schedulingaction.Intercept(f(g(h())))`. +func (c *SchedulingActionClient) Intercept(interceptors ...Interceptor) { + c.inters.SchedulingAction = append(c.inters.SchedulingAction, interceptors...) +} + +// Create returns a builder for creating a SchedulingAction entity. +func (c *SchedulingActionClient) Create() *SchedulingActionCreate { + mutation := newSchedulingActionMutation(c.config, OpCreate) + return &SchedulingActionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SchedulingAction entities. +func (c *SchedulingActionClient) CreateBulk(builders ...*SchedulingActionCreate) *SchedulingActionCreateBulk { + return &SchedulingActionCreateBulk{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 *SchedulingActionClient) MapCreateBulk(slice any, setFunc func(*SchedulingActionCreate, int)) *SchedulingActionCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SchedulingActionCreateBulk{err: fmt.Errorf("calling to SchedulingActionClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SchedulingActionCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SchedulingActionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SchedulingAction. +func (c *SchedulingActionClient) Update() *SchedulingActionUpdate { + mutation := newSchedulingActionMutation(c.config, OpUpdate) + return &SchedulingActionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SchedulingActionClient) UpdateOne(_m *SchedulingAction) *SchedulingActionUpdateOne { + mutation := newSchedulingActionMutation(c.config, OpUpdateOne, withSchedulingAction(_m)) + return &SchedulingActionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SchedulingActionClient) UpdateOneID(id int64) *SchedulingActionUpdateOne { + mutation := newSchedulingActionMutation(c.config, OpUpdateOne, withSchedulingActionID(id)) + return &SchedulingActionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SchedulingAction. +func (c *SchedulingActionClient) Delete() *SchedulingActionDelete { + mutation := newSchedulingActionMutation(c.config, OpDelete) + return &SchedulingActionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SchedulingActionClient) DeleteOne(_m *SchedulingAction) *SchedulingActionDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SchedulingActionClient) DeleteOneID(id int64) *SchedulingActionDeleteOne { + builder := c.Delete().Where(schedulingaction.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SchedulingActionDeleteOne{builder} +} + +// Query returns a query builder for SchedulingAction. +func (c *SchedulingActionClient) Query() *SchedulingActionQuery { + return &SchedulingActionQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSchedulingAction}, + inters: c.Interceptors(), + } +} + +// Get returns a SchedulingAction entity by its id. +func (c *SchedulingActionClient) Get(ctx context.Context, id int64) (*SchedulingAction, error) { + return c.Query().Where(schedulingaction.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SchedulingActionClient) GetX(ctx context.Context, id int64) *SchedulingAction { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *SchedulingActionClient) Hooks() []Hook { + return c.hooks.SchedulingAction +} + +// Interceptors returns the client interceptors. +func (c *SchedulingActionClient) Interceptors() []Interceptor { + return c.inters.SchedulingAction +} + +func (c *SchedulingActionClient) mutate(ctx context.Context, m *SchedulingActionMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SchedulingActionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SchedulingActionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SchedulingActionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SchedulingActionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown SchedulingAction mutation op: %q", m.Op()) + } +} + +// SchedulingPolicyClient is a client for the SchedulingPolicy schema. +type SchedulingPolicyClient struct { + config +} + +// NewSchedulingPolicyClient returns a client for the SchedulingPolicy from the given config. +func NewSchedulingPolicyClient(c config) *SchedulingPolicyClient { + return &SchedulingPolicyClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `schedulingpolicy.Hooks(f(g(h())))`. +func (c *SchedulingPolicyClient) Use(hooks ...Hook) { + c.hooks.SchedulingPolicy = append(c.hooks.SchedulingPolicy, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `schedulingpolicy.Intercept(f(g(h())))`. +func (c *SchedulingPolicyClient) Intercept(interceptors ...Interceptor) { + c.inters.SchedulingPolicy = append(c.inters.SchedulingPolicy, interceptors...) +} + +// Create returns a builder for creating a SchedulingPolicy entity. +func (c *SchedulingPolicyClient) Create() *SchedulingPolicyCreate { + mutation := newSchedulingPolicyMutation(c.config, OpCreate) + return &SchedulingPolicyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SchedulingPolicy entities. +func (c *SchedulingPolicyClient) CreateBulk(builders ...*SchedulingPolicyCreate) *SchedulingPolicyCreateBulk { + return &SchedulingPolicyCreateBulk{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 *SchedulingPolicyClient) MapCreateBulk(slice any, setFunc func(*SchedulingPolicyCreate, int)) *SchedulingPolicyCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SchedulingPolicyCreateBulk{err: fmt.Errorf("calling to SchedulingPolicyClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SchedulingPolicyCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SchedulingPolicyCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SchedulingPolicy. +func (c *SchedulingPolicyClient) Update() *SchedulingPolicyUpdate { + mutation := newSchedulingPolicyMutation(c.config, OpUpdate) + return &SchedulingPolicyUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SchedulingPolicyClient) UpdateOne(_m *SchedulingPolicy) *SchedulingPolicyUpdateOne { + mutation := newSchedulingPolicyMutation(c.config, OpUpdateOne, withSchedulingPolicy(_m)) + return &SchedulingPolicyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SchedulingPolicyClient) UpdateOneID(id int64) *SchedulingPolicyUpdateOne { + mutation := newSchedulingPolicyMutation(c.config, OpUpdateOne, withSchedulingPolicyID(id)) + return &SchedulingPolicyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SchedulingPolicy. +func (c *SchedulingPolicyClient) Delete() *SchedulingPolicyDelete { + mutation := newSchedulingPolicyMutation(c.config, OpDelete) + return &SchedulingPolicyDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SchedulingPolicyClient) DeleteOne(_m *SchedulingPolicy) *SchedulingPolicyDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SchedulingPolicyClient) DeleteOneID(id int64) *SchedulingPolicyDeleteOne { + builder := c.Delete().Where(schedulingpolicy.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SchedulingPolicyDeleteOne{builder} +} + +// Query returns a query builder for SchedulingPolicy. +func (c *SchedulingPolicyClient) Query() *SchedulingPolicyQuery { + return &SchedulingPolicyQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSchedulingPolicy}, + inters: c.Interceptors(), + } +} + +// Get returns a SchedulingPolicy entity by its id. +func (c *SchedulingPolicyClient) Get(ctx context.Context, id int64) (*SchedulingPolicy, error) { + return c.Query().Where(schedulingpolicy.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SchedulingPolicyClient) GetX(ctx context.Context, id int64) *SchedulingPolicy { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *SchedulingPolicyClient) Hooks() []Hook { + return c.hooks.SchedulingPolicy +} + +// Interceptors returns the client interceptors. +func (c *SchedulingPolicyClient) Interceptors() []Interceptor { + return c.inters.SchedulingPolicy +} + +func (c *SchedulingPolicyClient) mutate(ctx context.Context, m *SchedulingPolicyMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SchedulingPolicyCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SchedulingPolicyUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SchedulingPolicyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SchedulingPolicyDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown SchedulingPolicy mutation op: %q", m.Op()) + } +} + // SecuritySecretClient is a client for the SecuritySecret schema. type SecuritySecretClient struct { config @@ -6672,9 +6956,10 @@ type ( ChannelMonitorRequestTemplate, ErrorPassthroughRule, Group, IdempotencyRecord, IdentityAdoptionDecision, PaymentAuditLog, PaymentOrder, PaymentProviderInstance, PendingAuthSession, PromoCode, PromoCodeUsage, Proxy, - RedeemCode, SecuritySecret, Setting, SubscriptionPlan, TLSFingerprintProfile, - UsageCleanupTask, UsageLog, User, UserAllowedGroup, UserAttributeDefinition, - UserAttributeValue, UserPlatformQuota, UserSubscription []ent.Hook + RedeemCode, SchedulingAction, SchedulingPolicy, SecuritySecret, Setting, + SubscriptionPlan, TLSFingerprintProfile, UsageCleanupTask, UsageLog, User, + UserAllowedGroup, UserAttributeDefinition, UserAttributeValue, + UserPlatformQuota, UserSubscription []ent.Hook } inters struct { APIKey, Account, AccountGroup, Announcement, AnnouncementRead, AuthIdentity, @@ -6683,9 +6968,10 @@ type ( ChannelMonitorRequestTemplate, ErrorPassthroughRule, Group, IdempotencyRecord, IdentityAdoptionDecision, PaymentAuditLog, PaymentOrder, PaymentProviderInstance, PendingAuthSession, PromoCode, PromoCodeUsage, Proxy, - RedeemCode, SecuritySecret, Setting, SubscriptionPlan, TLSFingerprintProfile, - UsageCleanupTask, UsageLog, User, UserAllowedGroup, UserAttributeDefinition, - UserAttributeValue, UserPlatformQuota, UserSubscription []ent.Interceptor + RedeemCode, SchedulingAction, SchedulingPolicy, SecuritySecret, Setting, + SubscriptionPlan, TLSFingerprintProfile, UsageCleanupTask, UsageLog, User, + UserAllowedGroup, UserAttributeDefinition, UserAttributeValue, + UserPlatformQuota, UserSubscription []ent.Interceptor } ) diff --git a/backend/ent/ent.go b/backend/ent/ent.go index d23f61327ff1..2801c6dfc6db 100644 --- a/backend/ent/ent.go +++ b/backend/ent/ent.go @@ -38,6 +38,8 @@ import ( "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/subscriptionplan" @@ -136,6 +138,8 @@ func checkColumn(t, c string) error { promocodeusage.Table: promocodeusage.ValidColumn, proxy.Table: proxy.ValidColumn, redeemcode.Table: redeemcode.ValidColumn, + schedulingaction.Table: schedulingaction.ValidColumn, + schedulingpolicy.Table: schedulingpolicy.ValidColumn, securitysecret.Table: securitysecret.ValidColumn, setting.Table: setting.ValidColumn, subscriptionplan.Table: subscriptionplan.ValidColumn, diff --git a/backend/ent/hook/hook.go b/backend/ent/hook/hook.go index 181f2f99dbbd..3b0e8230cb75 100644 --- a/backend/ent/hook/hook.go +++ b/backend/ent/hook/hook.go @@ -321,6 +321,30 @@ func (f RedeemCodeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RedeemCodeMutation", m) } +// The SchedulingActionFunc type is an adapter to allow the use of ordinary +// function as SchedulingAction mutator. +type SchedulingActionFunc func(context.Context, *ent.SchedulingActionMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f SchedulingActionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.SchedulingActionMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SchedulingActionMutation", m) +} + +// The SchedulingPolicyFunc type is an adapter to allow the use of ordinary +// function as SchedulingPolicy mutator. +type SchedulingPolicyFunc func(context.Context, *ent.SchedulingPolicyMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f SchedulingPolicyFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.SchedulingPolicyMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SchedulingPolicyMutation", m) +} + // The SecuritySecretFunc type is an adapter to allow the use of ordinary // function as SecuritySecret mutator. type SecuritySecretFunc func(context.Context, *ent.SecuritySecretMutation) (ent.Value, error) diff --git a/backend/ent/intercept/intercept.go b/backend/ent/intercept/intercept.go index 7aeb07692ddf..9f71d009779f 100644 --- a/backend/ent/intercept/intercept.go +++ b/backend/ent/intercept/intercept.go @@ -35,6 +35,8 @@ import ( "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/subscriptionplan" @@ -807,6 +809,60 @@ func (f TraverseRedeemCode) Traverse(ctx context.Context, q ent.Query) error { return fmt.Errorf("unexpected query type %T. expect *ent.RedeemCodeQuery", q) } +// The SchedulingActionFunc type is an adapter to allow the use of ordinary function as a Querier. +type SchedulingActionFunc func(context.Context, *ent.SchedulingActionQuery) (ent.Value, error) + +// Query calls f(ctx, q). +func (f SchedulingActionFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) { + if q, ok := q.(*ent.SchedulingActionQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *ent.SchedulingActionQuery", q) +} + +// The TraverseSchedulingAction type is an adapter to allow the use of ordinary function as Traverser. +type TraverseSchedulingAction func(context.Context, *ent.SchedulingActionQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseSchedulingAction) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseSchedulingAction) Traverse(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.SchedulingActionQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *ent.SchedulingActionQuery", q) +} + +// The SchedulingPolicyFunc type is an adapter to allow the use of ordinary function as a Querier. +type SchedulingPolicyFunc func(context.Context, *ent.SchedulingPolicyQuery) (ent.Value, error) + +// Query calls f(ctx, q). +func (f SchedulingPolicyFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) { + if q, ok := q.(*ent.SchedulingPolicyQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *ent.SchedulingPolicyQuery", q) +} + +// The TraverseSchedulingPolicy type is an adapter to allow the use of ordinary function as Traverser. +type TraverseSchedulingPolicy func(context.Context, *ent.SchedulingPolicyQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseSchedulingPolicy) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseSchedulingPolicy) Traverse(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.SchedulingPolicyQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *ent.SchedulingPolicyQuery", q) +} + // The SecuritySecretFunc type is an adapter to allow the use of ordinary function as a Querier. type SecuritySecretFunc func(context.Context, *ent.SecuritySecretQuery) (ent.Value, error) @@ -1186,6 +1242,10 @@ func NewQuery(q ent.Query) (Query, error) { return &query[*ent.ProxyQuery, predicate.Proxy, proxy.OrderOption]{typ: ent.TypeProxy, tq: q}, nil case *ent.RedeemCodeQuery: return &query[*ent.RedeemCodeQuery, predicate.RedeemCode, redeemcode.OrderOption]{typ: ent.TypeRedeemCode, tq: q}, nil + case *ent.SchedulingActionQuery: + return &query[*ent.SchedulingActionQuery, predicate.SchedulingAction, schedulingaction.OrderOption]{typ: ent.TypeSchedulingAction, tq: q}, nil + case *ent.SchedulingPolicyQuery: + return &query[*ent.SchedulingPolicyQuery, predicate.SchedulingPolicy, schedulingpolicy.OrderOption]{typ: ent.TypeSchedulingPolicy, tq: q}, nil case *ent.SecuritySecretQuery: return &query[*ent.SecuritySecretQuery, predicate.SecuritySecret, securitysecret.OrderOption]{typ: ent.TypeSecuritySecret, tq: q}, nil case *ent.SettingQuery: diff --git a/backend/ent/migrate/schema.go b/backend/ent/migrate/schema.go index d3e8bc5448cd..81373c1b27c2 100644 --- a/backend/ent/migrate/schema.go +++ b/backend/ent/migrate/schema.go @@ -1411,6 +1411,71 @@ var ( }, }, } + // SchedulingActionsColumns holds the columns for the "scheduling_actions" table. + SchedulingActionsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "policy_id", Type: field.TypeInt64}, + {Name: "account_id", Type: field.TypeInt64}, + {Name: "monitor_id", Type: field.TypeInt64}, + {Name: "action", Type: field.TypeString, Size: 32}, + {Name: "reason", Type: field.TypeString, Size: 500, Default: ""}, + {Name: "original_priority", Type: field.TypeInt, Default: 0}, + {Name: "restored", Type: field.TypeBool, Default: false}, + {Name: "created_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"}, + } + // SchedulingActionsTable holds the schema information for the "scheduling_actions" table. + SchedulingActionsTable = &schema.Table{ + Name: "scheduling_actions", + Columns: SchedulingActionsColumns, + PrimaryKey: []*schema.Column{SchedulingActionsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "schedulingaction_policy_id_created_at", + Unique: false, + Columns: []*schema.Column{SchedulingActionsColumns[1], SchedulingActionsColumns[8]}, + }, + { + Name: "schedulingaction_account_id_restored", + Unique: false, + Columns: []*schema.Column{SchedulingActionsColumns[2], SchedulingActionsColumns[7]}, + }, + }, + } + // SchedulingPoliciesColumns holds the columns for the "scheduling_policies" table. + SchedulingPoliciesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, + {Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}}, + {Name: "name", Type: field.TypeString, Size: 100}, + {Name: "enabled", Type: field.TypeBool, Default: true}, + {Name: "monitor_id", Type: field.TypeInt64}, + {Name: "account_ids", Type: field.TypeJSON}, + {Name: "trigger_consecutive_failures", Type: field.TypeInt, Default: 3}, + {Name: "trigger_latency_ms", Type: field.TypeInt, Default: 0}, + {Name: "action_type", Type: field.TypeString, Size: 32, Default: "pause"}, + {Name: "pause_minutes", Type: field.TypeInt, Default: 0}, + {Name: "priority_delta", Type: field.TypeInt, Default: 10}, + {Name: "recover_consecutive_successes", Type: field.TypeInt, Default: 2}, + {Name: "cooldown_minutes", Type: field.TypeInt, Default: 10}, + } + // SchedulingPoliciesTable holds the schema information for the "scheduling_policies" table. + SchedulingPoliciesTable = &schema.Table{ + Name: "scheduling_policies", + Columns: SchedulingPoliciesColumns, + PrimaryKey: []*schema.Column{SchedulingPoliciesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "schedulingpolicy_monitor_id", + Unique: false, + Columns: []*schema.Column{SchedulingPoliciesColumns[5]}, + }, + { + Name: "schedulingpolicy_enabled", + Unique: false, + Columns: []*schema.Column{SchedulingPoliciesColumns[4]}, + }, + }, + } // SecuritySecretsColumns holds the columns for the "security_secrets" table. SecuritySecretsColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt64, Increment: true}, @@ -2012,6 +2077,8 @@ var ( PromoCodeUsagesTable, ProxiesTable, RedeemCodesTable, + SchedulingActionsTable, + SchedulingPoliciesTable, SecuritySecretsTable, SettingsTable, SubscriptionPlansTable, @@ -2128,6 +2195,12 @@ func init() { RedeemCodesTable.Annotation = &entsql.Annotation{ Table: "redeem_codes", } + SchedulingActionsTable.Annotation = &entsql.Annotation{ + Table: "scheduling_actions", + } + SchedulingPoliciesTable.Annotation = &entsql.Annotation{ + Table: "scheduling_policies", + } SecuritySecretsTable.Annotation = &entsql.Annotation{ Table: "security_secrets", } diff --git a/backend/ent/mutation.go b/backend/ent/mutation.go index 8d32773050c7..67762c5925cc 100644 --- a/backend/ent/mutation.go +++ b/backend/ent/mutation.go @@ -39,6 +39,8 @@ import ( "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/ent/setting" "github.com/Wei-Shaw/sub2api/ent/subscriptionplan" @@ -89,6 +91,8 @@ const ( TypePromoCodeUsage = "PromoCodeUsage" TypeProxy = "Proxy" TypeRedeemCode = "RedeemCode" + TypeSchedulingAction = "SchedulingAction" + TypeSchedulingPolicy = "SchedulingPolicy" TypeSecuritySecret = "SecuritySecret" TypeSetting = "Setting" TypeSubscriptionPlan = "SubscriptionPlan" @@ -37109,6 +37113,2069 @@ func (m *RedeemCodeMutation) ResetEdge(name string) error { return fmt.Errorf("unknown RedeemCode edge %s", name) } +// SchedulingActionMutation represents an operation that mutates the SchedulingAction nodes in the graph. +type SchedulingActionMutation struct { + config + op Op + typ string + id *int64 + policy_id *int64 + addpolicy_id *int64 + account_id *int64 + addaccount_id *int64 + monitor_id *int64 + addmonitor_id *int64 + action *string + reason *string + original_priority *int + addoriginal_priority *int + restored *bool + created_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*SchedulingAction, error) + predicates []predicate.SchedulingAction +} + +var _ ent.Mutation = (*SchedulingActionMutation)(nil) + +// schedulingactionOption allows management of the mutation configuration using functional options. +type schedulingactionOption func(*SchedulingActionMutation) + +// newSchedulingActionMutation creates new mutation for the SchedulingAction entity. +func newSchedulingActionMutation(c config, op Op, opts ...schedulingactionOption) *SchedulingActionMutation { + m := &SchedulingActionMutation{ + config: c, + op: op, + typ: TypeSchedulingAction, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSchedulingActionID sets the ID field of the mutation. +func withSchedulingActionID(id int64) schedulingactionOption { + return func(m *SchedulingActionMutation) { + var ( + err error + once sync.Once + value *SchedulingAction + ) + m.oldValue = func(ctx context.Context) (*SchedulingAction, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SchedulingAction.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSchedulingAction sets the old SchedulingAction of the mutation. +func withSchedulingAction(node *SchedulingAction) schedulingactionOption { + return func(m *SchedulingActionMutation) { + m.oldValue = func(context.Context) (*SchedulingAction, 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 SchedulingActionMutation) 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 SchedulingActionMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *SchedulingActionMutation) ID() (id int64, 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 *SchedulingActionMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().SchedulingAction.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetPolicyID sets the "policy_id" field. +func (m *SchedulingActionMutation) SetPolicyID(i int64) { + m.policy_id = &i + m.addpolicy_id = nil +} + +// PolicyID returns the value of the "policy_id" field in the mutation. +func (m *SchedulingActionMutation) PolicyID() (r int64, exists bool) { + v := m.policy_id + if v == nil { + return + } + return *v, true +} + +// OldPolicyID returns the old "policy_id" field's value of the SchedulingAction entity. +// If the SchedulingAction 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 *SchedulingActionMutation) OldPolicyID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPolicyID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPolicyID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPolicyID: %w", err) + } + return oldValue.PolicyID, nil +} + +// AddPolicyID adds i to the "policy_id" field. +func (m *SchedulingActionMutation) AddPolicyID(i int64) { + if m.addpolicy_id != nil { + *m.addpolicy_id += i + } else { + m.addpolicy_id = &i + } +} + +// AddedPolicyID returns the value that was added to the "policy_id" field in this mutation. +func (m *SchedulingActionMutation) AddedPolicyID() (r int64, exists bool) { + v := m.addpolicy_id + if v == nil { + return + } + return *v, true +} + +// ResetPolicyID resets all changes to the "policy_id" field. +func (m *SchedulingActionMutation) ResetPolicyID() { + m.policy_id = nil + m.addpolicy_id = nil +} + +// SetAccountID sets the "account_id" field. +func (m *SchedulingActionMutation) SetAccountID(i int64) { + m.account_id = &i + m.addaccount_id = nil +} + +// AccountID returns the value of the "account_id" field in the mutation. +func (m *SchedulingActionMutation) AccountID() (r int64, exists bool) { + v := m.account_id + if v == nil { + return + } + return *v, true +} + +// OldAccountID returns the old "account_id" field's value of the SchedulingAction entity. +// If the SchedulingAction 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 *SchedulingActionMutation) OldAccountID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAccountID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAccountID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAccountID: %w", err) + } + return oldValue.AccountID, nil +} + +// AddAccountID adds i to the "account_id" field. +func (m *SchedulingActionMutation) AddAccountID(i int64) { + if m.addaccount_id != nil { + *m.addaccount_id += i + } else { + m.addaccount_id = &i + } +} + +// AddedAccountID returns the value that was added to the "account_id" field in this mutation. +func (m *SchedulingActionMutation) AddedAccountID() (r int64, exists bool) { + v := m.addaccount_id + if v == nil { + return + } + return *v, true +} + +// ResetAccountID resets all changes to the "account_id" field. +func (m *SchedulingActionMutation) ResetAccountID() { + m.account_id = nil + m.addaccount_id = nil +} + +// SetMonitorID sets the "monitor_id" field. +func (m *SchedulingActionMutation) SetMonitorID(i int64) { + m.monitor_id = &i + m.addmonitor_id = nil +} + +// MonitorID returns the value of the "monitor_id" field in the mutation. +func (m *SchedulingActionMutation) MonitorID() (r int64, exists bool) { + v := m.monitor_id + if v == nil { + return + } + return *v, true +} + +// OldMonitorID returns the old "monitor_id" field's value of the SchedulingAction entity. +// If the SchedulingAction 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 *SchedulingActionMutation) OldMonitorID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMonitorID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMonitorID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMonitorID: %w", err) + } + return oldValue.MonitorID, nil +} + +// AddMonitorID adds i to the "monitor_id" field. +func (m *SchedulingActionMutation) AddMonitorID(i int64) { + if m.addmonitor_id != nil { + *m.addmonitor_id += i + } else { + m.addmonitor_id = &i + } +} + +// AddedMonitorID returns the value that was added to the "monitor_id" field in this mutation. +func (m *SchedulingActionMutation) AddedMonitorID() (r int64, exists bool) { + v := m.addmonitor_id + if v == nil { + return + } + return *v, true +} + +// ResetMonitorID resets all changes to the "monitor_id" field. +func (m *SchedulingActionMutation) ResetMonitorID() { + m.monitor_id = nil + m.addmonitor_id = nil +} + +// SetAction sets the "action" field. +func (m *SchedulingActionMutation) SetAction(s string) { + m.action = &s +} + +// Action returns the value of the "action" field in the mutation. +func (m *SchedulingActionMutation) Action() (r string, exists bool) { + v := m.action + if v == nil { + return + } + return *v, true +} + +// OldAction returns the old "action" field's value of the SchedulingAction entity. +// If the SchedulingAction 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 *SchedulingActionMutation) OldAction(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAction is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAction requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAction: %w", err) + } + return oldValue.Action, nil +} + +// ResetAction resets all changes to the "action" field. +func (m *SchedulingActionMutation) ResetAction() { + m.action = nil +} + +// SetReason sets the "reason" field. +func (m *SchedulingActionMutation) SetReason(s string) { + m.reason = &s +} + +// Reason returns the value of the "reason" field in the mutation. +func (m *SchedulingActionMutation) Reason() (r string, exists bool) { + v := m.reason + if v == nil { + return + } + return *v, true +} + +// OldReason returns the old "reason" field's value of the SchedulingAction entity. +// If the SchedulingAction 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 *SchedulingActionMutation) OldReason(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReason is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReason requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReason: %w", err) + } + return oldValue.Reason, nil +} + +// ResetReason resets all changes to the "reason" field. +func (m *SchedulingActionMutation) ResetReason() { + m.reason = nil +} + +// SetOriginalPriority sets the "original_priority" field. +func (m *SchedulingActionMutation) SetOriginalPriority(i int) { + m.original_priority = &i + m.addoriginal_priority = nil +} + +// OriginalPriority returns the value of the "original_priority" field in the mutation. +func (m *SchedulingActionMutation) OriginalPriority() (r int, exists bool) { + v := m.original_priority + if v == nil { + return + } + return *v, true +} + +// OldOriginalPriority returns the old "original_priority" field's value of the SchedulingAction entity. +// If the SchedulingAction 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 *SchedulingActionMutation) OldOriginalPriority(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOriginalPriority is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOriginalPriority requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOriginalPriority: %w", err) + } + return oldValue.OriginalPriority, nil +} + +// AddOriginalPriority adds i to the "original_priority" field. +func (m *SchedulingActionMutation) AddOriginalPriority(i int) { + if m.addoriginal_priority != nil { + *m.addoriginal_priority += i + } else { + m.addoriginal_priority = &i + } +} + +// AddedOriginalPriority returns the value that was added to the "original_priority" field in this mutation. +func (m *SchedulingActionMutation) AddedOriginalPriority() (r int, exists bool) { + v := m.addoriginal_priority + if v == nil { + return + } + return *v, true +} + +// ResetOriginalPriority resets all changes to the "original_priority" field. +func (m *SchedulingActionMutation) ResetOriginalPriority() { + m.original_priority = nil + m.addoriginal_priority = nil +} + +// SetRestored sets the "restored" field. +func (m *SchedulingActionMutation) SetRestored(b bool) { + m.restored = &b +} + +// Restored returns the value of the "restored" field in the mutation. +func (m *SchedulingActionMutation) Restored() (r bool, exists bool) { + v := m.restored + if v == nil { + return + } + return *v, true +} + +// OldRestored returns the old "restored" field's value of the SchedulingAction entity. +// If the SchedulingAction 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 *SchedulingActionMutation) OldRestored(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRestored is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRestored requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRestored: %w", err) + } + return oldValue.Restored, nil +} + +// ResetRestored resets all changes to the "restored" field. +func (m *SchedulingActionMutation) ResetRestored() { + m.restored = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *SchedulingActionMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SchedulingActionMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the SchedulingAction entity. +// If the SchedulingAction 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 *SchedulingActionMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *SchedulingActionMutation) ResetCreatedAt() { + m.created_at = nil +} + +// Where appends a list predicates to the SchedulingActionMutation builder. +func (m *SchedulingActionMutation) Where(ps ...predicate.SchedulingAction) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SchedulingActionMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SchedulingActionMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SchedulingAction, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SchedulingActionMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SchedulingActionMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SchedulingAction). +func (m *SchedulingActionMutation) 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 *SchedulingActionMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.policy_id != nil { + fields = append(fields, schedulingaction.FieldPolicyID) + } + if m.account_id != nil { + fields = append(fields, schedulingaction.FieldAccountID) + } + if m.monitor_id != nil { + fields = append(fields, schedulingaction.FieldMonitorID) + } + if m.action != nil { + fields = append(fields, schedulingaction.FieldAction) + } + if m.reason != nil { + fields = append(fields, schedulingaction.FieldReason) + } + if m.original_priority != nil { + fields = append(fields, schedulingaction.FieldOriginalPriority) + } + if m.restored != nil { + fields = append(fields, schedulingaction.FieldRestored) + } + if m.created_at != nil { + fields = append(fields, schedulingaction.FieldCreatedAt) + } + 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 *SchedulingActionMutation) Field(name string) (ent.Value, bool) { + switch name { + case schedulingaction.FieldPolicyID: + return m.PolicyID() + case schedulingaction.FieldAccountID: + return m.AccountID() + case schedulingaction.FieldMonitorID: + return m.MonitorID() + case schedulingaction.FieldAction: + return m.Action() + case schedulingaction.FieldReason: + return m.Reason() + case schedulingaction.FieldOriginalPriority: + return m.OriginalPriority() + case schedulingaction.FieldRestored: + return m.Restored() + case schedulingaction.FieldCreatedAt: + return m.CreatedAt() + } + 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 *SchedulingActionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case schedulingaction.FieldPolicyID: + return m.OldPolicyID(ctx) + case schedulingaction.FieldAccountID: + return m.OldAccountID(ctx) + case schedulingaction.FieldMonitorID: + return m.OldMonitorID(ctx) + case schedulingaction.FieldAction: + return m.OldAction(ctx) + case schedulingaction.FieldReason: + return m.OldReason(ctx) + case schedulingaction.FieldOriginalPriority: + return m.OldOriginalPriority(ctx) + case schedulingaction.FieldRestored: + return m.OldRestored(ctx) + case schedulingaction.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown SchedulingAction 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 *SchedulingActionMutation) SetField(name string, value ent.Value) error { + switch name { + case schedulingaction.FieldPolicyID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPolicyID(v) + return nil + case schedulingaction.FieldAccountID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAccountID(v) + return nil + case schedulingaction.FieldMonitorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMonitorID(v) + return nil + case schedulingaction.FieldAction: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAction(v) + return nil + case schedulingaction.FieldReason: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReason(v) + return nil + case schedulingaction.FieldOriginalPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOriginalPriority(v) + return nil + case schedulingaction.FieldRestored: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRestored(v) + return nil + case schedulingaction.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown SchedulingAction field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SchedulingActionMutation) AddedFields() []string { + var fields []string + if m.addpolicy_id != nil { + fields = append(fields, schedulingaction.FieldPolicyID) + } + if m.addaccount_id != nil { + fields = append(fields, schedulingaction.FieldAccountID) + } + if m.addmonitor_id != nil { + fields = append(fields, schedulingaction.FieldMonitorID) + } + if m.addoriginal_priority != nil { + fields = append(fields, schedulingaction.FieldOriginalPriority) + } + 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 *SchedulingActionMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case schedulingaction.FieldPolicyID: + return m.AddedPolicyID() + case schedulingaction.FieldAccountID: + return m.AddedAccountID() + case schedulingaction.FieldMonitorID: + return m.AddedMonitorID() + case schedulingaction.FieldOriginalPriority: + return m.AddedOriginalPriority() + } + 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 *SchedulingActionMutation) AddField(name string, value ent.Value) error { + switch name { + case schedulingaction.FieldPolicyID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPolicyID(v) + return nil + case schedulingaction.FieldAccountID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddAccountID(v) + return nil + case schedulingaction.FieldMonitorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMonitorID(v) + return nil + case schedulingaction.FieldOriginalPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOriginalPriority(v) + return nil + } + return fmt.Errorf("unknown SchedulingAction numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SchedulingActionMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SchedulingActionMutation) 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 *SchedulingActionMutation) ClearField(name string) error { + return fmt.Errorf("unknown SchedulingAction 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 *SchedulingActionMutation) ResetField(name string) error { + switch name { + case schedulingaction.FieldPolicyID: + m.ResetPolicyID() + return nil + case schedulingaction.FieldAccountID: + m.ResetAccountID() + return nil + case schedulingaction.FieldMonitorID: + m.ResetMonitorID() + return nil + case schedulingaction.FieldAction: + m.ResetAction() + return nil + case schedulingaction.FieldReason: + m.ResetReason() + return nil + case schedulingaction.FieldOriginalPriority: + m.ResetOriginalPriority() + return nil + case schedulingaction.FieldRestored: + m.ResetRestored() + return nil + case schedulingaction.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown SchedulingAction field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SchedulingActionMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SchedulingActionMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SchedulingActionMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SchedulingActionMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SchedulingActionMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SchedulingActionMutation) EdgeCleared(name string) bool { + 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 *SchedulingActionMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown SchedulingAction 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 *SchedulingActionMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown SchedulingAction edge %s", name) +} + +// SchedulingPolicyMutation represents an operation that mutates the SchedulingPolicy nodes in the graph. +type SchedulingPolicyMutation struct { + config + op Op + typ string + id *int64 + created_at *time.Time + updated_at *time.Time + name *string + enabled *bool + monitor_id *int64 + addmonitor_id *int64 + account_ids *[]int64 + appendaccount_ids []int64 + trigger_consecutive_failures *int + addtrigger_consecutive_failures *int + trigger_latency_ms *int + addtrigger_latency_ms *int + action_type *string + pause_minutes *int + addpause_minutes *int + priority_delta *int + addpriority_delta *int + recover_consecutive_successes *int + addrecover_consecutive_successes *int + cooldown_minutes *int + addcooldown_minutes *int + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*SchedulingPolicy, error) + predicates []predicate.SchedulingPolicy +} + +var _ ent.Mutation = (*SchedulingPolicyMutation)(nil) + +// schedulingpolicyOption allows management of the mutation configuration using functional options. +type schedulingpolicyOption func(*SchedulingPolicyMutation) + +// newSchedulingPolicyMutation creates new mutation for the SchedulingPolicy entity. +func newSchedulingPolicyMutation(c config, op Op, opts ...schedulingpolicyOption) *SchedulingPolicyMutation { + m := &SchedulingPolicyMutation{ + config: c, + op: op, + typ: TypeSchedulingPolicy, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSchedulingPolicyID sets the ID field of the mutation. +func withSchedulingPolicyID(id int64) schedulingpolicyOption { + return func(m *SchedulingPolicyMutation) { + var ( + err error + once sync.Once + value *SchedulingPolicy + ) + m.oldValue = func(ctx context.Context) (*SchedulingPolicy, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SchedulingPolicy.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSchedulingPolicy sets the old SchedulingPolicy of the mutation. +func withSchedulingPolicy(node *SchedulingPolicy) schedulingpolicyOption { + return func(m *SchedulingPolicyMutation) { + m.oldValue = func(context.Context) (*SchedulingPolicy, 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 SchedulingPolicyMutation) 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 SchedulingPolicyMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *SchedulingPolicyMutation) ID() (id int64, 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 *SchedulingPolicyMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().SchedulingPolicy.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *SchedulingPolicyMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SchedulingPolicyMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *SchedulingPolicyMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *SchedulingPolicyMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SchedulingPolicyMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *SchedulingPolicyMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetName sets the "name" field. +func (m *SchedulingPolicyMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *SchedulingPolicyMutation) 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 SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) 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 *SchedulingPolicyMutation) ResetName() { + m.name = nil +} + +// SetEnabled sets the "enabled" field. +func (m *SchedulingPolicyMutation) SetEnabled(b bool) { + m.enabled = &b +} + +// Enabled returns the value of the "enabled" field in the mutation. +func (m *SchedulingPolicyMutation) Enabled() (r bool, exists bool) { + v := m.enabled + if v == nil { + return + } + return *v, true +} + +// OldEnabled returns the old "enabled" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldEnabled(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEnabled is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEnabled requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEnabled: %w", err) + } + return oldValue.Enabled, nil +} + +// ResetEnabled resets all changes to the "enabled" field. +func (m *SchedulingPolicyMutation) ResetEnabled() { + m.enabled = nil +} + +// SetMonitorID sets the "monitor_id" field. +func (m *SchedulingPolicyMutation) SetMonitorID(i int64) { + m.monitor_id = &i + m.addmonitor_id = nil +} + +// MonitorID returns the value of the "monitor_id" field in the mutation. +func (m *SchedulingPolicyMutation) MonitorID() (r int64, exists bool) { + v := m.monitor_id + if v == nil { + return + } + return *v, true +} + +// OldMonitorID returns the old "monitor_id" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldMonitorID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMonitorID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMonitorID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMonitorID: %w", err) + } + return oldValue.MonitorID, nil +} + +// AddMonitorID adds i to the "monitor_id" field. +func (m *SchedulingPolicyMutation) AddMonitorID(i int64) { + if m.addmonitor_id != nil { + *m.addmonitor_id += i + } else { + m.addmonitor_id = &i + } +} + +// AddedMonitorID returns the value that was added to the "monitor_id" field in this mutation. +func (m *SchedulingPolicyMutation) AddedMonitorID() (r int64, exists bool) { + v := m.addmonitor_id + if v == nil { + return + } + return *v, true +} + +// ResetMonitorID resets all changes to the "monitor_id" field. +func (m *SchedulingPolicyMutation) ResetMonitorID() { + m.monitor_id = nil + m.addmonitor_id = nil +} + +// SetAccountIds sets the "account_ids" field. +func (m *SchedulingPolicyMutation) SetAccountIds(i []int64) { + m.account_ids = &i + m.appendaccount_ids = nil +} + +// AccountIds returns the value of the "account_ids" field in the mutation. +func (m *SchedulingPolicyMutation) AccountIds() (r []int64, exists bool) { + v := m.account_ids + if v == nil { + return + } + return *v, true +} + +// OldAccountIds returns the old "account_ids" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldAccountIds(ctx context.Context) (v []int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAccountIds is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAccountIds requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAccountIds: %w", err) + } + return oldValue.AccountIds, nil +} + +// AppendAccountIds adds i to the "account_ids" field. +func (m *SchedulingPolicyMutation) AppendAccountIds(i []int64) { + m.appendaccount_ids = append(m.appendaccount_ids, i...) +} + +// AppendedAccountIds returns the list of values that were appended to the "account_ids" field in this mutation. +func (m *SchedulingPolicyMutation) AppendedAccountIds() ([]int64, bool) { + if len(m.appendaccount_ids) == 0 { + return nil, false + } + return m.appendaccount_ids, true +} + +// ResetAccountIds resets all changes to the "account_ids" field. +func (m *SchedulingPolicyMutation) ResetAccountIds() { + m.account_ids = nil + m.appendaccount_ids = nil +} + +// SetTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field. +func (m *SchedulingPolicyMutation) SetTriggerConsecutiveFailures(i int) { + m.trigger_consecutive_failures = &i + m.addtrigger_consecutive_failures = nil +} + +// TriggerConsecutiveFailures returns the value of the "trigger_consecutive_failures" field in the mutation. +func (m *SchedulingPolicyMutation) TriggerConsecutiveFailures() (r int, exists bool) { + v := m.trigger_consecutive_failures + if v == nil { + return + } + return *v, true +} + +// OldTriggerConsecutiveFailures returns the old "trigger_consecutive_failures" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldTriggerConsecutiveFailures(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTriggerConsecutiveFailures is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTriggerConsecutiveFailures requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTriggerConsecutiveFailures: %w", err) + } + return oldValue.TriggerConsecutiveFailures, nil +} + +// AddTriggerConsecutiveFailures adds i to the "trigger_consecutive_failures" field. +func (m *SchedulingPolicyMutation) AddTriggerConsecutiveFailures(i int) { + if m.addtrigger_consecutive_failures != nil { + *m.addtrigger_consecutive_failures += i + } else { + m.addtrigger_consecutive_failures = &i + } +} + +// AddedTriggerConsecutiveFailures returns the value that was added to the "trigger_consecutive_failures" field in this mutation. +func (m *SchedulingPolicyMutation) AddedTriggerConsecutiveFailures() (r int, exists bool) { + v := m.addtrigger_consecutive_failures + if v == nil { + return + } + return *v, true +} + +// ResetTriggerConsecutiveFailures resets all changes to the "trigger_consecutive_failures" field. +func (m *SchedulingPolicyMutation) ResetTriggerConsecutiveFailures() { + m.trigger_consecutive_failures = nil + m.addtrigger_consecutive_failures = nil +} + +// SetTriggerLatencyMs sets the "trigger_latency_ms" field. +func (m *SchedulingPolicyMutation) SetTriggerLatencyMs(i int) { + m.trigger_latency_ms = &i + m.addtrigger_latency_ms = nil +} + +// TriggerLatencyMs returns the value of the "trigger_latency_ms" field in the mutation. +func (m *SchedulingPolicyMutation) TriggerLatencyMs() (r int, exists bool) { + v := m.trigger_latency_ms + if v == nil { + return + } + return *v, true +} + +// OldTriggerLatencyMs returns the old "trigger_latency_ms" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldTriggerLatencyMs(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTriggerLatencyMs is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTriggerLatencyMs requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTriggerLatencyMs: %w", err) + } + return oldValue.TriggerLatencyMs, nil +} + +// AddTriggerLatencyMs adds i to the "trigger_latency_ms" field. +func (m *SchedulingPolicyMutation) AddTriggerLatencyMs(i int) { + if m.addtrigger_latency_ms != nil { + *m.addtrigger_latency_ms += i + } else { + m.addtrigger_latency_ms = &i + } +} + +// AddedTriggerLatencyMs returns the value that was added to the "trigger_latency_ms" field in this mutation. +func (m *SchedulingPolicyMutation) AddedTriggerLatencyMs() (r int, exists bool) { + v := m.addtrigger_latency_ms + if v == nil { + return + } + return *v, true +} + +// ResetTriggerLatencyMs resets all changes to the "trigger_latency_ms" field. +func (m *SchedulingPolicyMutation) ResetTriggerLatencyMs() { + m.trigger_latency_ms = nil + m.addtrigger_latency_ms = nil +} + +// SetActionType sets the "action_type" field. +func (m *SchedulingPolicyMutation) SetActionType(s string) { + m.action_type = &s +} + +// ActionType returns the value of the "action_type" field in the mutation. +func (m *SchedulingPolicyMutation) ActionType() (r string, exists bool) { + v := m.action_type + if v == nil { + return + } + return *v, true +} + +// OldActionType returns the old "action_type" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldActionType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActionType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActionType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActionType: %w", err) + } + return oldValue.ActionType, nil +} + +// ResetActionType resets all changes to the "action_type" field. +func (m *SchedulingPolicyMutation) ResetActionType() { + m.action_type = nil +} + +// SetPauseMinutes sets the "pause_minutes" field. +func (m *SchedulingPolicyMutation) SetPauseMinutes(i int) { + m.pause_minutes = &i + m.addpause_minutes = nil +} + +// PauseMinutes returns the value of the "pause_minutes" field in the mutation. +func (m *SchedulingPolicyMutation) PauseMinutes() (r int, exists bool) { + v := m.pause_minutes + if v == nil { + return + } + return *v, true +} + +// OldPauseMinutes returns the old "pause_minutes" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldPauseMinutes(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPauseMinutes is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPauseMinutes requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPauseMinutes: %w", err) + } + return oldValue.PauseMinutes, nil +} + +// AddPauseMinutes adds i to the "pause_minutes" field. +func (m *SchedulingPolicyMutation) AddPauseMinutes(i int) { + if m.addpause_minutes != nil { + *m.addpause_minutes += i + } else { + m.addpause_minutes = &i + } +} + +// AddedPauseMinutes returns the value that was added to the "pause_minutes" field in this mutation. +func (m *SchedulingPolicyMutation) AddedPauseMinutes() (r int, exists bool) { + v := m.addpause_minutes + if v == nil { + return + } + return *v, true +} + +// ResetPauseMinutes resets all changes to the "pause_minutes" field. +func (m *SchedulingPolicyMutation) ResetPauseMinutes() { + m.pause_minutes = nil + m.addpause_minutes = nil +} + +// SetPriorityDelta sets the "priority_delta" field. +func (m *SchedulingPolicyMutation) SetPriorityDelta(i int) { + m.priority_delta = &i + m.addpriority_delta = nil +} + +// PriorityDelta returns the value of the "priority_delta" field in the mutation. +func (m *SchedulingPolicyMutation) PriorityDelta() (r int, exists bool) { + v := m.priority_delta + if v == nil { + return + } + return *v, true +} + +// OldPriorityDelta returns the old "priority_delta" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldPriorityDelta(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPriorityDelta is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPriorityDelta requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPriorityDelta: %w", err) + } + return oldValue.PriorityDelta, nil +} + +// AddPriorityDelta adds i to the "priority_delta" field. +func (m *SchedulingPolicyMutation) AddPriorityDelta(i int) { + if m.addpriority_delta != nil { + *m.addpriority_delta += i + } else { + m.addpriority_delta = &i + } +} + +// AddedPriorityDelta returns the value that was added to the "priority_delta" field in this mutation. +func (m *SchedulingPolicyMutation) AddedPriorityDelta() (r int, exists bool) { + v := m.addpriority_delta + if v == nil { + return + } + return *v, true +} + +// ResetPriorityDelta resets all changes to the "priority_delta" field. +func (m *SchedulingPolicyMutation) ResetPriorityDelta() { + m.priority_delta = nil + m.addpriority_delta = nil +} + +// SetRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field. +func (m *SchedulingPolicyMutation) SetRecoverConsecutiveSuccesses(i int) { + m.recover_consecutive_successes = &i + m.addrecover_consecutive_successes = nil +} + +// RecoverConsecutiveSuccesses returns the value of the "recover_consecutive_successes" field in the mutation. +func (m *SchedulingPolicyMutation) RecoverConsecutiveSuccesses() (r int, exists bool) { + v := m.recover_consecutive_successes + if v == nil { + return + } + return *v, true +} + +// OldRecoverConsecutiveSuccesses returns the old "recover_consecutive_successes" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldRecoverConsecutiveSuccesses(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRecoverConsecutiveSuccesses is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRecoverConsecutiveSuccesses requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRecoverConsecutiveSuccesses: %w", err) + } + return oldValue.RecoverConsecutiveSuccesses, nil +} + +// AddRecoverConsecutiveSuccesses adds i to the "recover_consecutive_successes" field. +func (m *SchedulingPolicyMutation) AddRecoverConsecutiveSuccesses(i int) { + if m.addrecover_consecutive_successes != nil { + *m.addrecover_consecutive_successes += i + } else { + m.addrecover_consecutive_successes = &i + } +} + +// AddedRecoverConsecutiveSuccesses returns the value that was added to the "recover_consecutive_successes" field in this mutation. +func (m *SchedulingPolicyMutation) AddedRecoverConsecutiveSuccesses() (r int, exists bool) { + v := m.addrecover_consecutive_successes + if v == nil { + return + } + return *v, true +} + +// ResetRecoverConsecutiveSuccesses resets all changes to the "recover_consecutive_successes" field. +func (m *SchedulingPolicyMutation) ResetRecoverConsecutiveSuccesses() { + m.recover_consecutive_successes = nil + m.addrecover_consecutive_successes = nil +} + +// SetCooldownMinutes sets the "cooldown_minutes" field. +func (m *SchedulingPolicyMutation) SetCooldownMinutes(i int) { + m.cooldown_minutes = &i + m.addcooldown_minutes = nil +} + +// CooldownMinutes returns the value of the "cooldown_minutes" field in the mutation. +func (m *SchedulingPolicyMutation) CooldownMinutes() (r int, exists bool) { + v := m.cooldown_minutes + if v == nil { + return + } + return *v, true +} + +// OldCooldownMinutes returns the old "cooldown_minutes" field's value of the SchedulingPolicy entity. +// If the SchedulingPolicy 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 *SchedulingPolicyMutation) OldCooldownMinutes(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCooldownMinutes is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCooldownMinutes requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCooldownMinutes: %w", err) + } + return oldValue.CooldownMinutes, nil +} + +// AddCooldownMinutes adds i to the "cooldown_minutes" field. +func (m *SchedulingPolicyMutation) AddCooldownMinutes(i int) { + if m.addcooldown_minutes != nil { + *m.addcooldown_minutes += i + } else { + m.addcooldown_minutes = &i + } +} + +// AddedCooldownMinutes returns the value that was added to the "cooldown_minutes" field in this mutation. +func (m *SchedulingPolicyMutation) AddedCooldownMinutes() (r int, exists bool) { + v := m.addcooldown_minutes + if v == nil { + return + } + return *v, true +} + +// ResetCooldownMinutes resets all changes to the "cooldown_minutes" field. +func (m *SchedulingPolicyMutation) ResetCooldownMinutes() { + m.cooldown_minutes = nil + m.addcooldown_minutes = nil +} + +// Where appends a list predicates to the SchedulingPolicyMutation builder. +func (m *SchedulingPolicyMutation) Where(ps ...predicate.SchedulingPolicy) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SchedulingPolicyMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SchedulingPolicyMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SchedulingPolicy, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SchedulingPolicyMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SchedulingPolicyMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SchedulingPolicy). +func (m *SchedulingPolicyMutation) 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 *SchedulingPolicyMutation) Fields() []string { + fields := make([]string, 0, 13) + if m.created_at != nil { + fields = append(fields, schedulingpolicy.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, schedulingpolicy.FieldUpdatedAt) + } + if m.name != nil { + fields = append(fields, schedulingpolicy.FieldName) + } + if m.enabled != nil { + fields = append(fields, schedulingpolicy.FieldEnabled) + } + if m.monitor_id != nil { + fields = append(fields, schedulingpolicy.FieldMonitorID) + } + if m.account_ids != nil { + fields = append(fields, schedulingpolicy.FieldAccountIds) + } + if m.trigger_consecutive_failures != nil { + fields = append(fields, schedulingpolicy.FieldTriggerConsecutiveFailures) + } + if m.trigger_latency_ms != nil { + fields = append(fields, schedulingpolicy.FieldTriggerLatencyMs) + } + if m.action_type != nil { + fields = append(fields, schedulingpolicy.FieldActionType) + } + if m.pause_minutes != nil { + fields = append(fields, schedulingpolicy.FieldPauseMinutes) + } + if m.priority_delta != nil { + fields = append(fields, schedulingpolicy.FieldPriorityDelta) + } + if m.recover_consecutive_successes != nil { + fields = append(fields, schedulingpolicy.FieldRecoverConsecutiveSuccesses) + } + if m.cooldown_minutes != nil { + fields = append(fields, schedulingpolicy.FieldCooldownMinutes) + } + 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 *SchedulingPolicyMutation) Field(name string) (ent.Value, bool) { + switch name { + case schedulingpolicy.FieldCreatedAt: + return m.CreatedAt() + case schedulingpolicy.FieldUpdatedAt: + return m.UpdatedAt() + case schedulingpolicy.FieldName: + return m.Name() + case schedulingpolicy.FieldEnabled: + return m.Enabled() + case schedulingpolicy.FieldMonitorID: + return m.MonitorID() + case schedulingpolicy.FieldAccountIds: + return m.AccountIds() + case schedulingpolicy.FieldTriggerConsecutiveFailures: + return m.TriggerConsecutiveFailures() + case schedulingpolicy.FieldTriggerLatencyMs: + return m.TriggerLatencyMs() + case schedulingpolicy.FieldActionType: + return m.ActionType() + case schedulingpolicy.FieldPauseMinutes: + return m.PauseMinutes() + case schedulingpolicy.FieldPriorityDelta: + return m.PriorityDelta() + case schedulingpolicy.FieldRecoverConsecutiveSuccesses: + return m.RecoverConsecutiveSuccesses() + case schedulingpolicy.FieldCooldownMinutes: + return m.CooldownMinutes() + } + 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 *SchedulingPolicyMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case schedulingpolicy.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case schedulingpolicy.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case schedulingpolicy.FieldName: + return m.OldName(ctx) + case schedulingpolicy.FieldEnabled: + return m.OldEnabled(ctx) + case schedulingpolicy.FieldMonitorID: + return m.OldMonitorID(ctx) + case schedulingpolicy.FieldAccountIds: + return m.OldAccountIds(ctx) + case schedulingpolicy.FieldTriggerConsecutiveFailures: + return m.OldTriggerConsecutiveFailures(ctx) + case schedulingpolicy.FieldTriggerLatencyMs: + return m.OldTriggerLatencyMs(ctx) + case schedulingpolicy.FieldActionType: + return m.OldActionType(ctx) + case schedulingpolicy.FieldPauseMinutes: + return m.OldPauseMinutes(ctx) + case schedulingpolicy.FieldPriorityDelta: + return m.OldPriorityDelta(ctx) + case schedulingpolicy.FieldRecoverConsecutiveSuccesses: + return m.OldRecoverConsecutiveSuccesses(ctx) + case schedulingpolicy.FieldCooldownMinutes: + return m.OldCooldownMinutes(ctx) + } + return nil, fmt.Errorf("unknown SchedulingPolicy 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 *SchedulingPolicyMutation) SetField(name string, value ent.Value) error { + switch name { + case schedulingpolicy.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case schedulingpolicy.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case schedulingpolicy.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case schedulingpolicy.FieldEnabled: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEnabled(v) + return nil + case schedulingpolicy.FieldMonitorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMonitorID(v) + return nil + case schedulingpolicy.FieldAccountIds: + v, ok := value.([]int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAccountIds(v) + return nil + case schedulingpolicy.FieldTriggerConsecutiveFailures: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTriggerConsecutiveFailures(v) + return nil + case schedulingpolicy.FieldTriggerLatencyMs: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTriggerLatencyMs(v) + return nil + case schedulingpolicy.FieldActionType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActionType(v) + return nil + case schedulingpolicy.FieldPauseMinutes: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPauseMinutes(v) + return nil + case schedulingpolicy.FieldPriorityDelta: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPriorityDelta(v) + return nil + case schedulingpolicy.FieldRecoverConsecutiveSuccesses: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRecoverConsecutiveSuccesses(v) + return nil + case schedulingpolicy.FieldCooldownMinutes: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCooldownMinutes(v) + return nil + } + return fmt.Errorf("unknown SchedulingPolicy field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SchedulingPolicyMutation) AddedFields() []string { + var fields []string + if m.addmonitor_id != nil { + fields = append(fields, schedulingpolicy.FieldMonitorID) + } + if m.addtrigger_consecutive_failures != nil { + fields = append(fields, schedulingpolicy.FieldTriggerConsecutiveFailures) + } + if m.addtrigger_latency_ms != nil { + fields = append(fields, schedulingpolicy.FieldTriggerLatencyMs) + } + if m.addpause_minutes != nil { + fields = append(fields, schedulingpolicy.FieldPauseMinutes) + } + if m.addpriority_delta != nil { + fields = append(fields, schedulingpolicy.FieldPriorityDelta) + } + if m.addrecover_consecutive_successes != nil { + fields = append(fields, schedulingpolicy.FieldRecoverConsecutiveSuccesses) + } + if m.addcooldown_minutes != nil { + fields = append(fields, schedulingpolicy.FieldCooldownMinutes) + } + 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 *SchedulingPolicyMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case schedulingpolicy.FieldMonitorID: + return m.AddedMonitorID() + case schedulingpolicy.FieldTriggerConsecutiveFailures: + return m.AddedTriggerConsecutiveFailures() + case schedulingpolicy.FieldTriggerLatencyMs: + return m.AddedTriggerLatencyMs() + case schedulingpolicy.FieldPauseMinutes: + return m.AddedPauseMinutes() + case schedulingpolicy.FieldPriorityDelta: + return m.AddedPriorityDelta() + case schedulingpolicy.FieldRecoverConsecutiveSuccesses: + return m.AddedRecoverConsecutiveSuccesses() + case schedulingpolicy.FieldCooldownMinutes: + return m.AddedCooldownMinutes() + } + 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 *SchedulingPolicyMutation) AddField(name string, value ent.Value) error { + switch name { + case schedulingpolicy.FieldMonitorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMonitorID(v) + return nil + case schedulingpolicy.FieldTriggerConsecutiveFailures: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTriggerConsecutiveFailures(v) + return nil + case schedulingpolicy.FieldTriggerLatencyMs: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTriggerLatencyMs(v) + return nil + case schedulingpolicy.FieldPauseMinutes: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPauseMinutes(v) + return nil + case schedulingpolicy.FieldPriorityDelta: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPriorityDelta(v) + return nil + case schedulingpolicy.FieldRecoverConsecutiveSuccesses: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddRecoverConsecutiveSuccesses(v) + return nil + case schedulingpolicy.FieldCooldownMinutes: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCooldownMinutes(v) + return nil + } + return fmt.Errorf("unknown SchedulingPolicy numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SchedulingPolicyMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SchedulingPolicyMutation) 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 *SchedulingPolicyMutation) ClearField(name string) error { + return fmt.Errorf("unknown SchedulingPolicy 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 *SchedulingPolicyMutation) ResetField(name string) error { + switch name { + case schedulingpolicy.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case schedulingpolicy.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case schedulingpolicy.FieldName: + m.ResetName() + return nil + case schedulingpolicy.FieldEnabled: + m.ResetEnabled() + return nil + case schedulingpolicy.FieldMonitorID: + m.ResetMonitorID() + return nil + case schedulingpolicy.FieldAccountIds: + m.ResetAccountIds() + return nil + case schedulingpolicy.FieldTriggerConsecutiveFailures: + m.ResetTriggerConsecutiveFailures() + return nil + case schedulingpolicy.FieldTriggerLatencyMs: + m.ResetTriggerLatencyMs() + return nil + case schedulingpolicy.FieldActionType: + m.ResetActionType() + return nil + case schedulingpolicy.FieldPauseMinutes: + m.ResetPauseMinutes() + return nil + case schedulingpolicy.FieldPriorityDelta: + m.ResetPriorityDelta() + return nil + case schedulingpolicy.FieldRecoverConsecutiveSuccesses: + m.ResetRecoverConsecutiveSuccesses() + return nil + case schedulingpolicy.FieldCooldownMinutes: + m.ResetCooldownMinutes() + return nil + } + return fmt.Errorf("unknown SchedulingPolicy field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SchedulingPolicyMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SchedulingPolicyMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SchedulingPolicyMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SchedulingPolicyMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SchedulingPolicyMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SchedulingPolicyMutation) EdgeCleared(name string) bool { + 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 *SchedulingPolicyMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown SchedulingPolicy 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 *SchedulingPolicyMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown SchedulingPolicy edge %s", name) +} + // SecuritySecretMutation represents an operation that mutates the SecuritySecret nodes in the graph. type SecuritySecretMutation struct { config diff --git a/backend/ent/predicate/predicate.go b/backend/ent/predicate/predicate.go index 8d18d38151a7..9bcf7e2610aa 100644 --- a/backend/ent/predicate/predicate.go +++ b/backend/ent/predicate/predicate.go @@ -84,6 +84,12 @@ type Proxy func(*sql.Selector) // RedeemCode is the predicate function for redeemcode builders. type RedeemCode func(*sql.Selector) +// SchedulingAction is the predicate function for schedulingaction builders. +type SchedulingAction func(*sql.Selector) + +// SchedulingPolicy is the predicate function for schedulingpolicy builders. +type SchedulingPolicy func(*sql.Selector) + // SecuritySecret is the predicate function for securitysecret builders. type SecuritySecret func(*sql.Selector) diff --git a/backend/ent/runtime/runtime.go b/backend/ent/runtime/runtime.go index d47e7d143bba..5d2f22e0fcb0 100644 --- a/backend/ent/runtime/runtime.go +++ b/backend/ent/runtime/runtime.go @@ -31,6 +31,8 @@ import ( "github.com/Wei-Shaw/sub2api/ent/promocodeusage" "github.com/Wei-Shaw/sub2api/ent/proxy" "github.com/Wei-Shaw/sub2api/ent/redeemcode" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" "github.com/Wei-Shaw/sub2api/ent/schema" "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/ent/setting" @@ -1631,6 +1633,109 @@ func init() { redeemcodeDescValidityDays := redeemcodeFields[10].Descriptor() // redeemcode.DefaultValidityDays holds the default value on creation for the validity_days field. redeemcode.DefaultValidityDays = redeemcodeDescValidityDays.Default.(int) + schedulingactionFields := schema.SchedulingAction{}.Fields() + _ = schedulingactionFields + // schedulingactionDescAction is the schema descriptor for action field. + schedulingactionDescAction := schedulingactionFields[3].Descriptor() + // schedulingaction.ActionValidator is a validator for the "action" field. It is called by the builders before save. + schedulingaction.ActionValidator = schedulingactionDescAction.Validators[0].(func(string) error) + // schedulingactionDescReason is the schema descriptor for reason field. + schedulingactionDescReason := schedulingactionFields[4].Descriptor() + // schedulingaction.DefaultReason holds the default value on creation for the reason field. + schedulingaction.DefaultReason = schedulingactionDescReason.Default.(string) + // schedulingaction.ReasonValidator is a validator for the "reason" field. It is called by the builders before save. + schedulingaction.ReasonValidator = schedulingactionDescReason.Validators[0].(func(string) error) + // schedulingactionDescOriginalPriority is the schema descriptor for original_priority field. + schedulingactionDescOriginalPriority := schedulingactionFields[5].Descriptor() + // schedulingaction.DefaultOriginalPriority holds the default value on creation for the original_priority field. + schedulingaction.DefaultOriginalPriority = schedulingactionDescOriginalPriority.Default.(int) + // schedulingactionDescRestored is the schema descriptor for restored field. + schedulingactionDescRestored := schedulingactionFields[6].Descriptor() + // schedulingaction.DefaultRestored holds the default value on creation for the restored field. + schedulingaction.DefaultRestored = schedulingactionDescRestored.Default.(bool) + schedulingpolicyMixin := schema.SchedulingPolicy{}.Mixin() + schedulingpolicyMixinFields0 := schedulingpolicyMixin[0].Fields() + _ = schedulingpolicyMixinFields0 + schedulingpolicyFields := schema.SchedulingPolicy{}.Fields() + _ = schedulingpolicyFields + // schedulingpolicyDescCreatedAt is the schema descriptor for created_at field. + schedulingpolicyDescCreatedAt := schedulingpolicyMixinFields0[0].Descriptor() + // schedulingpolicy.DefaultCreatedAt holds the default value on creation for the created_at field. + schedulingpolicy.DefaultCreatedAt = schedulingpolicyDescCreatedAt.Default.(func() time.Time) + // schedulingpolicyDescUpdatedAt is the schema descriptor for updated_at field. + schedulingpolicyDescUpdatedAt := schedulingpolicyMixinFields0[1].Descriptor() + // schedulingpolicy.DefaultUpdatedAt holds the default value on creation for the updated_at field. + schedulingpolicy.DefaultUpdatedAt = schedulingpolicyDescUpdatedAt.Default.(func() time.Time) + // schedulingpolicy.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + schedulingpolicy.UpdateDefaultUpdatedAt = schedulingpolicyDescUpdatedAt.UpdateDefault.(func() time.Time) + // schedulingpolicyDescName is the schema descriptor for name field. + schedulingpolicyDescName := schedulingpolicyFields[0].Descriptor() + // schedulingpolicy.NameValidator is a validator for the "name" field. It is called by the builders before save. + schedulingpolicy.NameValidator = func() func(string) error { + validators := schedulingpolicyDescName.Validators + fns := [...]func(string) error{ + validators[0].(func(string) error), + validators[1].(func(string) error), + } + return func(name string) error { + for _, fn := range fns { + if err := fn(name); err != nil { + return err + } + } + return nil + } + }() + // schedulingpolicyDescEnabled is the schema descriptor for enabled field. + schedulingpolicyDescEnabled := schedulingpolicyFields[1].Descriptor() + // schedulingpolicy.DefaultEnabled holds the default value on creation for the enabled field. + schedulingpolicy.DefaultEnabled = schedulingpolicyDescEnabled.Default.(bool) + // schedulingpolicyDescAccountIds is the schema descriptor for account_ids field. + schedulingpolicyDescAccountIds := schedulingpolicyFields[3].Descriptor() + // schedulingpolicy.DefaultAccountIds holds the default value on creation for the account_ids field. + schedulingpolicy.DefaultAccountIds = schedulingpolicyDescAccountIds.Default.([]int64) + // schedulingpolicyDescTriggerConsecutiveFailures is the schema descriptor for trigger_consecutive_failures field. + schedulingpolicyDescTriggerConsecutiveFailures := schedulingpolicyFields[4].Descriptor() + // schedulingpolicy.DefaultTriggerConsecutiveFailures holds the default value on creation for the trigger_consecutive_failures field. + schedulingpolicy.DefaultTriggerConsecutiveFailures = schedulingpolicyDescTriggerConsecutiveFailures.Default.(int) + // schedulingpolicy.TriggerConsecutiveFailuresValidator is a validator for the "trigger_consecutive_failures" field. It is called by the builders before save. + schedulingpolicy.TriggerConsecutiveFailuresValidator = schedulingpolicyDescTriggerConsecutiveFailures.Validators[0].(func(int) error) + // schedulingpolicyDescTriggerLatencyMs is the schema descriptor for trigger_latency_ms field. + schedulingpolicyDescTriggerLatencyMs := schedulingpolicyFields[5].Descriptor() + // schedulingpolicy.DefaultTriggerLatencyMs holds the default value on creation for the trigger_latency_ms field. + schedulingpolicy.DefaultTriggerLatencyMs = schedulingpolicyDescTriggerLatencyMs.Default.(int) + // schedulingpolicy.TriggerLatencyMsValidator is a validator for the "trigger_latency_ms" field. It is called by the builders before save. + schedulingpolicy.TriggerLatencyMsValidator = schedulingpolicyDescTriggerLatencyMs.Validators[0].(func(int) error) + // schedulingpolicyDescActionType is the schema descriptor for action_type field. + schedulingpolicyDescActionType := schedulingpolicyFields[6].Descriptor() + // schedulingpolicy.DefaultActionType holds the default value on creation for the action_type field. + schedulingpolicy.DefaultActionType = schedulingpolicyDescActionType.Default.(string) + // schedulingpolicy.ActionTypeValidator is a validator for the "action_type" field. It is called by the builders before save. + schedulingpolicy.ActionTypeValidator = schedulingpolicyDescActionType.Validators[0].(func(string) error) + // schedulingpolicyDescPauseMinutes is the schema descriptor for pause_minutes field. + schedulingpolicyDescPauseMinutes := schedulingpolicyFields[7].Descriptor() + // schedulingpolicy.DefaultPauseMinutes holds the default value on creation for the pause_minutes field. + schedulingpolicy.DefaultPauseMinutes = schedulingpolicyDescPauseMinutes.Default.(int) + // schedulingpolicy.PauseMinutesValidator is a validator for the "pause_minutes" field. It is called by the builders before save. + schedulingpolicy.PauseMinutesValidator = schedulingpolicyDescPauseMinutes.Validators[0].(func(int) error) + // schedulingpolicyDescPriorityDelta is the schema descriptor for priority_delta field. + schedulingpolicyDescPriorityDelta := schedulingpolicyFields[8].Descriptor() + // schedulingpolicy.DefaultPriorityDelta holds the default value on creation for the priority_delta field. + schedulingpolicy.DefaultPriorityDelta = schedulingpolicyDescPriorityDelta.Default.(int) + // schedulingpolicy.PriorityDeltaValidator is a validator for the "priority_delta" field. It is called by the builders before save. + schedulingpolicy.PriorityDeltaValidator = schedulingpolicyDescPriorityDelta.Validators[0].(func(int) error) + // schedulingpolicyDescRecoverConsecutiveSuccesses is the schema descriptor for recover_consecutive_successes field. + schedulingpolicyDescRecoverConsecutiveSuccesses := schedulingpolicyFields[9].Descriptor() + // schedulingpolicy.DefaultRecoverConsecutiveSuccesses holds the default value on creation for the recover_consecutive_successes field. + schedulingpolicy.DefaultRecoverConsecutiveSuccesses = schedulingpolicyDescRecoverConsecutiveSuccesses.Default.(int) + // schedulingpolicy.RecoverConsecutiveSuccessesValidator is a validator for the "recover_consecutive_successes" field. It is called by the builders before save. + schedulingpolicy.RecoverConsecutiveSuccessesValidator = schedulingpolicyDescRecoverConsecutiveSuccesses.Validators[0].(func(int) error) + // schedulingpolicyDescCooldownMinutes is the schema descriptor for cooldown_minutes field. + schedulingpolicyDescCooldownMinutes := schedulingpolicyFields[10].Descriptor() + // schedulingpolicy.DefaultCooldownMinutes holds the default value on creation for the cooldown_minutes field. + schedulingpolicy.DefaultCooldownMinutes = schedulingpolicyDescCooldownMinutes.Default.(int) + // schedulingpolicy.CooldownMinutesValidator is a validator for the "cooldown_minutes" field. It is called by the builders before save. + schedulingpolicy.CooldownMinutesValidator = schedulingpolicyDescCooldownMinutes.Validators[0].(func(int) error) securitysecretMixin := schema.SecuritySecret{}.Mixin() securitysecretMixinFields0 := securitysecretMixin[0].Fields() _ = securitysecretMixinFields0 diff --git a/backend/ent/schedulingaction.go b/backend/ent/schedulingaction.go new file mode 100644 index 000000000000..aecb2eb380ec --- /dev/null +++ b/backend/ent/schedulingaction.go @@ -0,0 +1,185 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" +) + +// SchedulingAction is the model entity for the SchedulingAction schema. +type SchedulingAction struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // PolicyID holds the value of the "policy_id" field. + PolicyID int64 `json:"policy_id,omitempty"` + // AccountID holds the value of the "account_id" field. + AccountID int64 `json:"account_id,omitempty"` + // MonitorID holds the value of the "monitor_id" field. + MonitorID int64 `json:"monitor_id,omitempty"` + // pause / deprioritize / recover + Action string `json:"action,omitempty"` + // Reason holds the value of the "reason" field. + Reason string `json:"reason,omitempty"` + // deprioritize 动作执行前的账号优先级,恢复时还原 + OriginalPriority int `json:"original_priority,omitempty"` + // 该动作是否已被恢复(recover 动作本身恒为 true) + Restored bool `json:"restored,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*SchedulingAction) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case schedulingaction.FieldRestored: + values[i] = new(sql.NullBool) + case schedulingaction.FieldID, schedulingaction.FieldPolicyID, schedulingaction.FieldAccountID, schedulingaction.FieldMonitorID, schedulingaction.FieldOriginalPriority: + values[i] = new(sql.NullInt64) + case schedulingaction.FieldAction, schedulingaction.FieldReason: + values[i] = new(sql.NullString) + case schedulingaction.FieldCreatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the SchedulingAction fields. +func (_m *SchedulingAction) 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 schedulingaction.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case schedulingaction.FieldPolicyID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field policy_id", values[i]) + } else if value.Valid { + _m.PolicyID = value.Int64 + } + case schedulingaction.FieldAccountID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field account_id", values[i]) + } else if value.Valid { + _m.AccountID = value.Int64 + } + case schedulingaction.FieldMonitorID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field monitor_id", values[i]) + } else if value.Valid { + _m.MonitorID = value.Int64 + } + case schedulingaction.FieldAction: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field action", values[i]) + } else if value.Valid { + _m.Action = value.String + } + case schedulingaction.FieldReason: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field reason", values[i]) + } else if value.Valid { + _m.Reason = value.String + } + case schedulingaction.FieldOriginalPriority: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field original_priority", values[i]) + } else if value.Valid { + _m.OriginalPriority = int(value.Int64) + } + case schedulingaction.FieldRestored: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field restored", values[i]) + } else if value.Valid { + _m.Restored = value.Bool + } + case schedulingaction.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the SchedulingAction. +// This includes values selected through modifiers, order, etc. +func (_m *SchedulingAction) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this SchedulingAction. +// Note that you need to call SchedulingAction.Unwrap() before calling this method if this SchedulingAction +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *SchedulingAction) Update() *SchedulingActionUpdateOne { + return NewSchedulingActionClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the SchedulingAction 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 (_m *SchedulingAction) Unwrap() *SchedulingAction { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: SchedulingAction is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *SchedulingAction) String() string { + var builder strings.Builder + builder.WriteString("SchedulingAction(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("policy_id=") + builder.WriteString(fmt.Sprintf("%v", _m.PolicyID)) + builder.WriteString(", ") + builder.WriteString("account_id=") + builder.WriteString(fmt.Sprintf("%v", _m.AccountID)) + builder.WriteString(", ") + builder.WriteString("monitor_id=") + builder.WriteString(fmt.Sprintf("%v", _m.MonitorID)) + builder.WriteString(", ") + builder.WriteString("action=") + builder.WriteString(_m.Action) + builder.WriteString(", ") + builder.WriteString("reason=") + builder.WriteString(_m.Reason) + builder.WriteString(", ") + builder.WriteString("original_priority=") + builder.WriteString(fmt.Sprintf("%v", _m.OriginalPriority)) + builder.WriteString(", ") + builder.WriteString("restored=") + builder.WriteString(fmt.Sprintf("%v", _m.Restored)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// SchedulingActions is a parsable slice of SchedulingAction. +type SchedulingActions []*SchedulingAction diff --git a/backend/ent/schedulingaction/schedulingaction.go b/backend/ent/schedulingaction/schedulingaction.go new file mode 100644 index 000000000000..17b7b23247ae --- /dev/null +++ b/backend/ent/schedulingaction/schedulingaction.go @@ -0,0 +1,116 @@ +// Code generated by ent, DO NOT EDIT. + +package schedulingaction + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the schedulingaction type in the database. + Label = "scheduling_action" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldPolicyID holds the string denoting the policy_id field in the database. + FieldPolicyID = "policy_id" + // FieldAccountID holds the string denoting the account_id field in the database. + FieldAccountID = "account_id" + // FieldMonitorID holds the string denoting the monitor_id field in the database. + FieldMonitorID = "monitor_id" + // FieldAction holds the string denoting the action field in the database. + FieldAction = "action" + // FieldReason holds the string denoting the reason field in the database. + FieldReason = "reason" + // FieldOriginalPriority holds the string denoting the original_priority field in the database. + FieldOriginalPriority = "original_priority" + // FieldRestored holds the string denoting the restored field in the database. + FieldRestored = "restored" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // Table holds the table name of the schedulingaction in the database. + Table = "scheduling_actions" +) + +// Columns holds all SQL columns for schedulingaction fields. +var Columns = []string{ + FieldID, + FieldPolicyID, + FieldAccountID, + FieldMonitorID, + FieldAction, + FieldReason, + FieldOriginalPriority, + FieldRestored, + FieldCreatedAt, +} + +// 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 +} + +var ( + // ActionValidator is a validator for the "action" field. It is called by the builders before save. + ActionValidator func(string) error + // DefaultReason holds the default value on creation for the "reason" field. + DefaultReason string + // ReasonValidator is a validator for the "reason" field. It is called by the builders before save. + ReasonValidator func(string) error + // DefaultOriginalPriority holds the default value on creation for the "original_priority" field. + DefaultOriginalPriority int + // DefaultRestored holds the default value on creation for the "restored" field. + DefaultRestored bool +) + +// OrderOption defines the ordering options for the SchedulingAction 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() +} + +// ByPolicyID orders the results by the policy_id field. +func ByPolicyID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPolicyID, opts...).ToFunc() +} + +// ByAccountID orders the results by the account_id field. +func ByAccountID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAccountID, opts...).ToFunc() +} + +// ByMonitorID orders the results by the monitor_id field. +func ByMonitorID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMonitorID, opts...).ToFunc() +} + +// ByAction orders the results by the action field. +func ByAction(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAction, opts...).ToFunc() +} + +// ByReason orders the results by the reason field. +func ByReason(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReason, opts...).ToFunc() +} + +// ByOriginalPriority orders the results by the original_priority field. +func ByOriginalPriority(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOriginalPriority, opts...).ToFunc() +} + +// ByRestored orders the results by the restored field. +func ByRestored(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRestored, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} diff --git a/backend/ent/schedulingaction/where.go b/backend/ent/schedulingaction/where.go new file mode 100644 index 000000000000..8cf091f82b80 --- /dev/null +++ b/backend/ent/schedulingaction/where.go @@ -0,0 +1,450 @@ +// Code generated by ent, DO NOT EDIT. + +package schedulingaction + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "github.com/Wei-Shaw/sub2api/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLTE(FieldID, id)) +} + +// PolicyID applies equality check predicate on the "policy_id" field. It's identical to PolicyIDEQ. +func PolicyID(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldPolicyID, v)) +} + +// AccountID applies equality check predicate on the "account_id" field. It's identical to AccountIDEQ. +func AccountID(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldAccountID, v)) +} + +// MonitorID applies equality check predicate on the "monitor_id" field. It's identical to MonitorIDEQ. +func MonitorID(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldMonitorID, v)) +} + +// Action applies equality check predicate on the "action" field. It's identical to ActionEQ. +func Action(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldAction, v)) +} + +// Reason applies equality check predicate on the "reason" field. It's identical to ReasonEQ. +func Reason(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldReason, v)) +} + +// OriginalPriority applies equality check predicate on the "original_priority" field. It's identical to OriginalPriorityEQ. +func OriginalPriority(v int) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldOriginalPriority, v)) +} + +// Restored applies equality check predicate on the "restored" field. It's identical to RestoredEQ. +func Restored(v bool) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldRestored, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldCreatedAt, v)) +} + +// PolicyIDEQ applies the EQ predicate on the "policy_id" field. +func PolicyIDEQ(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldPolicyID, v)) +} + +// PolicyIDNEQ applies the NEQ predicate on the "policy_id" field. +func PolicyIDNEQ(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNEQ(FieldPolicyID, v)) +} + +// PolicyIDIn applies the In predicate on the "policy_id" field. +func PolicyIDIn(vs ...int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldIn(FieldPolicyID, vs...)) +} + +// PolicyIDNotIn applies the NotIn predicate on the "policy_id" field. +func PolicyIDNotIn(vs ...int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNotIn(FieldPolicyID, vs...)) +} + +// PolicyIDGT applies the GT predicate on the "policy_id" field. +func PolicyIDGT(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGT(FieldPolicyID, v)) +} + +// PolicyIDGTE applies the GTE predicate on the "policy_id" field. +func PolicyIDGTE(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGTE(FieldPolicyID, v)) +} + +// PolicyIDLT applies the LT predicate on the "policy_id" field. +func PolicyIDLT(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLT(FieldPolicyID, v)) +} + +// PolicyIDLTE applies the LTE predicate on the "policy_id" field. +func PolicyIDLTE(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLTE(FieldPolicyID, v)) +} + +// AccountIDEQ applies the EQ predicate on the "account_id" field. +func AccountIDEQ(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldAccountID, v)) +} + +// AccountIDNEQ applies the NEQ predicate on the "account_id" field. +func AccountIDNEQ(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNEQ(FieldAccountID, v)) +} + +// AccountIDIn applies the In predicate on the "account_id" field. +func AccountIDIn(vs ...int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldIn(FieldAccountID, vs...)) +} + +// AccountIDNotIn applies the NotIn predicate on the "account_id" field. +func AccountIDNotIn(vs ...int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNotIn(FieldAccountID, vs...)) +} + +// AccountIDGT applies the GT predicate on the "account_id" field. +func AccountIDGT(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGT(FieldAccountID, v)) +} + +// AccountIDGTE applies the GTE predicate on the "account_id" field. +func AccountIDGTE(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGTE(FieldAccountID, v)) +} + +// AccountIDLT applies the LT predicate on the "account_id" field. +func AccountIDLT(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLT(FieldAccountID, v)) +} + +// AccountIDLTE applies the LTE predicate on the "account_id" field. +func AccountIDLTE(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLTE(FieldAccountID, v)) +} + +// MonitorIDEQ applies the EQ predicate on the "monitor_id" field. +func MonitorIDEQ(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldMonitorID, v)) +} + +// MonitorIDNEQ applies the NEQ predicate on the "monitor_id" field. +func MonitorIDNEQ(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNEQ(FieldMonitorID, v)) +} + +// MonitorIDIn applies the In predicate on the "monitor_id" field. +func MonitorIDIn(vs ...int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldIn(FieldMonitorID, vs...)) +} + +// MonitorIDNotIn applies the NotIn predicate on the "monitor_id" field. +func MonitorIDNotIn(vs ...int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNotIn(FieldMonitorID, vs...)) +} + +// MonitorIDGT applies the GT predicate on the "monitor_id" field. +func MonitorIDGT(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGT(FieldMonitorID, v)) +} + +// MonitorIDGTE applies the GTE predicate on the "monitor_id" field. +func MonitorIDGTE(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGTE(FieldMonitorID, v)) +} + +// MonitorIDLT applies the LT predicate on the "monitor_id" field. +func MonitorIDLT(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLT(FieldMonitorID, v)) +} + +// MonitorIDLTE applies the LTE predicate on the "monitor_id" field. +func MonitorIDLTE(v int64) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLTE(FieldMonitorID, v)) +} + +// ActionEQ applies the EQ predicate on the "action" field. +func ActionEQ(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldAction, v)) +} + +// ActionNEQ applies the NEQ predicate on the "action" field. +func ActionNEQ(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNEQ(FieldAction, v)) +} + +// ActionIn applies the In predicate on the "action" field. +func ActionIn(vs ...string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldIn(FieldAction, vs...)) +} + +// ActionNotIn applies the NotIn predicate on the "action" field. +func ActionNotIn(vs ...string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNotIn(FieldAction, vs...)) +} + +// ActionGT applies the GT predicate on the "action" field. +func ActionGT(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGT(FieldAction, v)) +} + +// ActionGTE applies the GTE predicate on the "action" field. +func ActionGTE(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGTE(FieldAction, v)) +} + +// ActionLT applies the LT predicate on the "action" field. +func ActionLT(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLT(FieldAction, v)) +} + +// ActionLTE applies the LTE predicate on the "action" field. +func ActionLTE(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLTE(FieldAction, v)) +} + +// ActionContains applies the Contains predicate on the "action" field. +func ActionContains(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldContains(FieldAction, v)) +} + +// ActionHasPrefix applies the HasPrefix predicate on the "action" field. +func ActionHasPrefix(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldHasPrefix(FieldAction, v)) +} + +// ActionHasSuffix applies the HasSuffix predicate on the "action" field. +func ActionHasSuffix(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldHasSuffix(FieldAction, v)) +} + +// ActionEqualFold applies the EqualFold predicate on the "action" field. +func ActionEqualFold(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEqualFold(FieldAction, v)) +} + +// ActionContainsFold applies the ContainsFold predicate on the "action" field. +func ActionContainsFold(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldContainsFold(FieldAction, v)) +} + +// ReasonEQ applies the EQ predicate on the "reason" field. +func ReasonEQ(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldReason, v)) +} + +// ReasonNEQ applies the NEQ predicate on the "reason" field. +func ReasonNEQ(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNEQ(FieldReason, v)) +} + +// ReasonIn applies the In predicate on the "reason" field. +func ReasonIn(vs ...string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldIn(FieldReason, vs...)) +} + +// ReasonNotIn applies the NotIn predicate on the "reason" field. +func ReasonNotIn(vs ...string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNotIn(FieldReason, vs...)) +} + +// ReasonGT applies the GT predicate on the "reason" field. +func ReasonGT(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGT(FieldReason, v)) +} + +// ReasonGTE applies the GTE predicate on the "reason" field. +func ReasonGTE(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGTE(FieldReason, v)) +} + +// ReasonLT applies the LT predicate on the "reason" field. +func ReasonLT(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLT(FieldReason, v)) +} + +// ReasonLTE applies the LTE predicate on the "reason" field. +func ReasonLTE(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLTE(FieldReason, v)) +} + +// ReasonContains applies the Contains predicate on the "reason" field. +func ReasonContains(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldContains(FieldReason, v)) +} + +// ReasonHasPrefix applies the HasPrefix predicate on the "reason" field. +func ReasonHasPrefix(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldHasPrefix(FieldReason, v)) +} + +// ReasonHasSuffix applies the HasSuffix predicate on the "reason" field. +func ReasonHasSuffix(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldHasSuffix(FieldReason, v)) +} + +// ReasonEqualFold applies the EqualFold predicate on the "reason" field. +func ReasonEqualFold(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEqualFold(FieldReason, v)) +} + +// ReasonContainsFold applies the ContainsFold predicate on the "reason" field. +func ReasonContainsFold(v string) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldContainsFold(FieldReason, v)) +} + +// OriginalPriorityEQ applies the EQ predicate on the "original_priority" field. +func OriginalPriorityEQ(v int) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldOriginalPriority, v)) +} + +// OriginalPriorityNEQ applies the NEQ predicate on the "original_priority" field. +func OriginalPriorityNEQ(v int) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNEQ(FieldOriginalPriority, v)) +} + +// OriginalPriorityIn applies the In predicate on the "original_priority" field. +func OriginalPriorityIn(vs ...int) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldIn(FieldOriginalPriority, vs...)) +} + +// OriginalPriorityNotIn applies the NotIn predicate on the "original_priority" field. +func OriginalPriorityNotIn(vs ...int) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNotIn(FieldOriginalPriority, vs...)) +} + +// OriginalPriorityGT applies the GT predicate on the "original_priority" field. +func OriginalPriorityGT(v int) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGT(FieldOriginalPriority, v)) +} + +// OriginalPriorityGTE applies the GTE predicate on the "original_priority" field. +func OriginalPriorityGTE(v int) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGTE(FieldOriginalPriority, v)) +} + +// OriginalPriorityLT applies the LT predicate on the "original_priority" field. +func OriginalPriorityLT(v int) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLT(FieldOriginalPriority, v)) +} + +// OriginalPriorityLTE applies the LTE predicate on the "original_priority" field. +func OriginalPriorityLTE(v int) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLTE(FieldOriginalPriority, v)) +} + +// RestoredEQ applies the EQ predicate on the "restored" field. +func RestoredEQ(v bool) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldRestored, v)) +} + +// RestoredNEQ applies the NEQ predicate on the "restored" field. +func RestoredNEQ(v bool) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNEQ(FieldRestored, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.FieldLTE(FieldCreatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.SchedulingAction) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.SchedulingAction) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.SchedulingAction) predicate.SchedulingAction { + return predicate.SchedulingAction(sql.NotPredicates(p)) +} diff --git a/backend/ent/schedulingaction_create.go b/backend/ent/schedulingaction_create.go new file mode 100644 index 000000000000..2949678c1434 --- /dev/null +++ b/backend/ent/schedulingaction_create.go @@ -0,0 +1,930 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" +) + +// SchedulingActionCreate is the builder for creating a SchedulingAction entity. +type SchedulingActionCreate struct { + config + mutation *SchedulingActionMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetPolicyID sets the "policy_id" field. +func (_c *SchedulingActionCreate) SetPolicyID(v int64) *SchedulingActionCreate { + _c.mutation.SetPolicyID(v) + return _c +} + +// SetAccountID sets the "account_id" field. +func (_c *SchedulingActionCreate) SetAccountID(v int64) *SchedulingActionCreate { + _c.mutation.SetAccountID(v) + return _c +} + +// SetMonitorID sets the "monitor_id" field. +func (_c *SchedulingActionCreate) SetMonitorID(v int64) *SchedulingActionCreate { + _c.mutation.SetMonitorID(v) + return _c +} + +// SetAction sets the "action" field. +func (_c *SchedulingActionCreate) SetAction(v string) *SchedulingActionCreate { + _c.mutation.SetAction(v) + return _c +} + +// SetReason sets the "reason" field. +func (_c *SchedulingActionCreate) SetReason(v string) *SchedulingActionCreate { + _c.mutation.SetReason(v) + return _c +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_c *SchedulingActionCreate) SetNillableReason(v *string) *SchedulingActionCreate { + if v != nil { + _c.SetReason(*v) + } + return _c +} + +// SetOriginalPriority sets the "original_priority" field. +func (_c *SchedulingActionCreate) SetOriginalPriority(v int) *SchedulingActionCreate { + _c.mutation.SetOriginalPriority(v) + return _c +} + +// SetNillableOriginalPriority sets the "original_priority" field if the given value is not nil. +func (_c *SchedulingActionCreate) SetNillableOriginalPriority(v *int) *SchedulingActionCreate { + if v != nil { + _c.SetOriginalPriority(*v) + } + return _c +} + +// SetRestored sets the "restored" field. +func (_c *SchedulingActionCreate) SetRestored(v bool) *SchedulingActionCreate { + _c.mutation.SetRestored(v) + return _c +} + +// SetNillableRestored sets the "restored" field if the given value is not nil. +func (_c *SchedulingActionCreate) SetNillableRestored(v *bool) *SchedulingActionCreate { + if v != nil { + _c.SetRestored(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *SchedulingActionCreate) SetCreatedAt(v time.Time) *SchedulingActionCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// Mutation returns the SchedulingActionMutation object of the builder. +func (_c *SchedulingActionCreate) Mutation() *SchedulingActionMutation { + return _c.mutation +} + +// Save creates the SchedulingAction in the database. +func (_c *SchedulingActionCreate) Save(ctx context.Context) (*SchedulingAction, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *SchedulingActionCreate) SaveX(ctx context.Context) *SchedulingAction { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SchedulingActionCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SchedulingActionCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *SchedulingActionCreate) defaults() { + if _, ok := _c.mutation.Reason(); !ok { + v := schedulingaction.DefaultReason + _c.mutation.SetReason(v) + } + if _, ok := _c.mutation.OriginalPriority(); !ok { + v := schedulingaction.DefaultOriginalPriority + _c.mutation.SetOriginalPriority(v) + } + if _, ok := _c.mutation.Restored(); !ok { + v := schedulingaction.DefaultRestored + _c.mutation.SetRestored(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *SchedulingActionCreate) check() error { + if _, ok := _c.mutation.PolicyID(); !ok { + return &ValidationError{Name: "policy_id", err: errors.New(`ent: missing required field "SchedulingAction.policy_id"`)} + } + if _, ok := _c.mutation.AccountID(); !ok { + return &ValidationError{Name: "account_id", err: errors.New(`ent: missing required field "SchedulingAction.account_id"`)} + } + if _, ok := _c.mutation.MonitorID(); !ok { + return &ValidationError{Name: "monitor_id", err: errors.New(`ent: missing required field "SchedulingAction.monitor_id"`)} + } + if _, ok := _c.mutation.Action(); !ok { + return &ValidationError{Name: "action", err: errors.New(`ent: missing required field "SchedulingAction.action"`)} + } + if v, ok := _c.mutation.Action(); ok { + if err := schedulingaction.ActionValidator(v); err != nil { + return &ValidationError{Name: "action", err: fmt.Errorf(`ent: validator failed for field "SchedulingAction.action": %w`, err)} + } + } + if _, ok := _c.mutation.Reason(); !ok { + return &ValidationError{Name: "reason", err: errors.New(`ent: missing required field "SchedulingAction.reason"`)} + } + if v, ok := _c.mutation.Reason(); ok { + if err := schedulingaction.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`ent: validator failed for field "SchedulingAction.reason": %w`, err)} + } + } + if _, ok := _c.mutation.OriginalPriority(); !ok { + return &ValidationError{Name: "original_priority", err: errors.New(`ent: missing required field "SchedulingAction.original_priority"`)} + } + if _, ok := _c.mutation.Restored(); !ok { + return &ValidationError{Name: "restored", err: errors.New(`ent: missing required field "SchedulingAction.restored"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "SchedulingAction.created_at"`)} + } + return nil +} + +func (_c *SchedulingActionCreate) sqlSave(ctx context.Context) (*SchedulingAction, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *SchedulingActionCreate) createSpec() (*SchedulingAction, *sqlgraph.CreateSpec) { + var ( + _node = &SchedulingAction{config: _c.config} + _spec = sqlgraph.NewCreateSpec(schedulingaction.Table, sqlgraph.NewFieldSpec(schedulingaction.FieldID, field.TypeInt64)) + ) + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.PolicyID(); ok { + _spec.SetField(schedulingaction.FieldPolicyID, field.TypeInt64, value) + _node.PolicyID = value + } + if value, ok := _c.mutation.AccountID(); ok { + _spec.SetField(schedulingaction.FieldAccountID, field.TypeInt64, value) + _node.AccountID = value + } + if value, ok := _c.mutation.MonitorID(); ok { + _spec.SetField(schedulingaction.FieldMonitorID, field.TypeInt64, value) + _node.MonitorID = value + } + if value, ok := _c.mutation.Action(); ok { + _spec.SetField(schedulingaction.FieldAction, field.TypeString, value) + _node.Action = value + } + if value, ok := _c.mutation.Reason(); ok { + _spec.SetField(schedulingaction.FieldReason, field.TypeString, value) + _node.Reason = value + } + if value, ok := _c.mutation.OriginalPriority(); ok { + _spec.SetField(schedulingaction.FieldOriginalPriority, field.TypeInt, value) + _node.OriginalPriority = value + } + if value, ok := _c.mutation.Restored(); ok { + _spec.SetField(schedulingaction.FieldRestored, field.TypeBool, value) + _node.Restored = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(schedulingaction.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.SchedulingAction.Create(). +// SetPolicyID(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.SchedulingActionUpsert) { +// SetPolicyID(v+v). +// }). +// Exec(ctx) +func (_c *SchedulingActionCreate) OnConflict(opts ...sql.ConflictOption) *SchedulingActionUpsertOne { + _c.conflict = opts + return &SchedulingActionUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.SchedulingAction.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *SchedulingActionCreate) OnConflictColumns(columns ...string) *SchedulingActionUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &SchedulingActionUpsertOne{ + create: _c, + } +} + +type ( + // SchedulingActionUpsertOne is the builder for "upsert"-ing + // one SchedulingAction node. + SchedulingActionUpsertOne struct { + create *SchedulingActionCreate + } + + // SchedulingActionUpsert is the "OnConflict" setter. + SchedulingActionUpsert struct { + *sql.UpdateSet + } +) + +// SetPolicyID sets the "policy_id" field. +func (u *SchedulingActionUpsert) SetPolicyID(v int64) *SchedulingActionUpsert { + u.Set(schedulingaction.FieldPolicyID, v) + return u +} + +// UpdatePolicyID sets the "policy_id" field to the value that was provided on create. +func (u *SchedulingActionUpsert) UpdatePolicyID() *SchedulingActionUpsert { + u.SetExcluded(schedulingaction.FieldPolicyID) + return u +} + +// AddPolicyID adds v to the "policy_id" field. +func (u *SchedulingActionUpsert) AddPolicyID(v int64) *SchedulingActionUpsert { + u.Add(schedulingaction.FieldPolicyID, v) + return u +} + +// SetAccountID sets the "account_id" field. +func (u *SchedulingActionUpsert) SetAccountID(v int64) *SchedulingActionUpsert { + u.Set(schedulingaction.FieldAccountID, v) + return u +} + +// UpdateAccountID sets the "account_id" field to the value that was provided on create. +func (u *SchedulingActionUpsert) UpdateAccountID() *SchedulingActionUpsert { + u.SetExcluded(schedulingaction.FieldAccountID) + return u +} + +// AddAccountID adds v to the "account_id" field. +func (u *SchedulingActionUpsert) AddAccountID(v int64) *SchedulingActionUpsert { + u.Add(schedulingaction.FieldAccountID, v) + return u +} + +// SetMonitorID sets the "monitor_id" field. +func (u *SchedulingActionUpsert) SetMonitorID(v int64) *SchedulingActionUpsert { + u.Set(schedulingaction.FieldMonitorID, v) + return u +} + +// UpdateMonitorID sets the "monitor_id" field to the value that was provided on create. +func (u *SchedulingActionUpsert) UpdateMonitorID() *SchedulingActionUpsert { + u.SetExcluded(schedulingaction.FieldMonitorID) + return u +} + +// AddMonitorID adds v to the "monitor_id" field. +func (u *SchedulingActionUpsert) AddMonitorID(v int64) *SchedulingActionUpsert { + u.Add(schedulingaction.FieldMonitorID, v) + return u +} + +// SetAction sets the "action" field. +func (u *SchedulingActionUpsert) SetAction(v string) *SchedulingActionUpsert { + u.Set(schedulingaction.FieldAction, v) + return u +} + +// UpdateAction sets the "action" field to the value that was provided on create. +func (u *SchedulingActionUpsert) UpdateAction() *SchedulingActionUpsert { + u.SetExcluded(schedulingaction.FieldAction) + return u +} + +// SetReason sets the "reason" field. +func (u *SchedulingActionUpsert) SetReason(v string) *SchedulingActionUpsert { + u.Set(schedulingaction.FieldReason, v) + return u +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *SchedulingActionUpsert) UpdateReason() *SchedulingActionUpsert { + u.SetExcluded(schedulingaction.FieldReason) + return u +} + +// SetOriginalPriority sets the "original_priority" field. +func (u *SchedulingActionUpsert) SetOriginalPriority(v int) *SchedulingActionUpsert { + u.Set(schedulingaction.FieldOriginalPriority, v) + return u +} + +// UpdateOriginalPriority sets the "original_priority" field to the value that was provided on create. +func (u *SchedulingActionUpsert) UpdateOriginalPriority() *SchedulingActionUpsert { + u.SetExcluded(schedulingaction.FieldOriginalPriority) + return u +} + +// AddOriginalPriority adds v to the "original_priority" field. +func (u *SchedulingActionUpsert) AddOriginalPriority(v int) *SchedulingActionUpsert { + u.Add(schedulingaction.FieldOriginalPriority, v) + return u +} + +// SetRestored sets the "restored" field. +func (u *SchedulingActionUpsert) SetRestored(v bool) *SchedulingActionUpsert { + u.Set(schedulingaction.FieldRestored, v) + return u +} + +// UpdateRestored sets the "restored" field to the value that was provided on create. +func (u *SchedulingActionUpsert) UpdateRestored() *SchedulingActionUpsert { + u.SetExcluded(schedulingaction.FieldRestored) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.SchedulingAction.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *SchedulingActionUpsertOne) UpdateNewValues() *SchedulingActionUpsertOne { + 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.CreatedAt(); exists { + s.SetIgnore(schedulingaction.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.SchedulingAction.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SchedulingActionUpsertOne) Ignore() *SchedulingActionUpsertOne { + 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 *SchedulingActionUpsertOne) DoNothing() *SchedulingActionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SchedulingActionCreate.OnConflict +// documentation for more info. +func (u *SchedulingActionUpsertOne) Update(set func(*SchedulingActionUpsert)) *SchedulingActionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SchedulingActionUpsert{UpdateSet: update}) + })) + return u +} + +// SetPolicyID sets the "policy_id" field. +func (u *SchedulingActionUpsertOne) SetPolicyID(v int64) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetPolicyID(v) + }) +} + +// AddPolicyID adds v to the "policy_id" field. +func (u *SchedulingActionUpsertOne) AddPolicyID(v int64) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.AddPolicyID(v) + }) +} + +// UpdatePolicyID sets the "policy_id" field to the value that was provided on create. +func (u *SchedulingActionUpsertOne) UpdatePolicyID() *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdatePolicyID() + }) +} + +// SetAccountID sets the "account_id" field. +func (u *SchedulingActionUpsertOne) SetAccountID(v int64) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetAccountID(v) + }) +} + +// AddAccountID adds v to the "account_id" field. +func (u *SchedulingActionUpsertOne) AddAccountID(v int64) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.AddAccountID(v) + }) +} + +// UpdateAccountID sets the "account_id" field to the value that was provided on create. +func (u *SchedulingActionUpsertOne) UpdateAccountID() *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateAccountID() + }) +} + +// SetMonitorID sets the "monitor_id" field. +func (u *SchedulingActionUpsertOne) SetMonitorID(v int64) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetMonitorID(v) + }) +} + +// AddMonitorID adds v to the "monitor_id" field. +func (u *SchedulingActionUpsertOne) AddMonitorID(v int64) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.AddMonitorID(v) + }) +} + +// UpdateMonitorID sets the "monitor_id" field to the value that was provided on create. +func (u *SchedulingActionUpsertOne) UpdateMonitorID() *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateMonitorID() + }) +} + +// SetAction sets the "action" field. +func (u *SchedulingActionUpsertOne) SetAction(v string) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetAction(v) + }) +} + +// UpdateAction sets the "action" field to the value that was provided on create. +func (u *SchedulingActionUpsertOne) UpdateAction() *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateAction() + }) +} + +// SetReason sets the "reason" field. +func (u *SchedulingActionUpsertOne) SetReason(v string) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetReason(v) + }) +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *SchedulingActionUpsertOne) UpdateReason() *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateReason() + }) +} + +// SetOriginalPriority sets the "original_priority" field. +func (u *SchedulingActionUpsertOne) SetOriginalPriority(v int) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetOriginalPriority(v) + }) +} + +// AddOriginalPriority adds v to the "original_priority" field. +func (u *SchedulingActionUpsertOne) AddOriginalPriority(v int) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.AddOriginalPriority(v) + }) +} + +// UpdateOriginalPriority sets the "original_priority" field to the value that was provided on create. +func (u *SchedulingActionUpsertOne) UpdateOriginalPriority() *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateOriginalPriority() + }) +} + +// SetRestored sets the "restored" field. +func (u *SchedulingActionUpsertOne) SetRestored(v bool) *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetRestored(v) + }) +} + +// UpdateRestored sets the "restored" field to the value that was provided on create. +func (u *SchedulingActionUpsertOne) UpdateRestored() *SchedulingActionUpsertOne { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateRestored() + }) +} + +// Exec executes the query. +func (u *SchedulingActionUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for SchedulingActionCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SchedulingActionUpsertOne) 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 *SchedulingActionUpsertOne) ID(ctx context.Context) (id int64, err error) { + 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 *SchedulingActionUpsertOne) IDX(ctx context.Context) int64 { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// SchedulingActionCreateBulk is the builder for creating many SchedulingAction entities in bulk. +type SchedulingActionCreateBulk struct { + config + err error + builders []*SchedulingActionCreate + conflict []sql.ConflictOption +} + +// Save creates the SchedulingAction entities in the database. +func (_c *SchedulingActionCreateBulk) Save(ctx context.Context) ([]*SchedulingAction, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*SchedulingAction, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*SchedulingActionMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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 + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *SchedulingActionCreateBulk) SaveX(ctx context.Context) []*SchedulingAction { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SchedulingActionCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SchedulingActionCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.SchedulingAction.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.SchedulingActionUpsert) { +// SetPolicyID(v+v). +// }). +// Exec(ctx) +func (_c *SchedulingActionCreateBulk) OnConflict(opts ...sql.ConflictOption) *SchedulingActionUpsertBulk { + _c.conflict = opts + return &SchedulingActionUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.SchedulingAction.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *SchedulingActionCreateBulk) OnConflictColumns(columns ...string) *SchedulingActionUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &SchedulingActionUpsertBulk{ + create: _c, + } +} + +// SchedulingActionUpsertBulk is the builder for "upsert"-ing +// a bulk of SchedulingAction nodes. +type SchedulingActionUpsertBulk struct { + create *SchedulingActionCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.SchedulingAction.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *SchedulingActionUpsertBulk) UpdateNewValues() *SchedulingActionUpsertBulk { + 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.CreatedAt(); exists { + s.SetIgnore(schedulingaction.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.SchedulingAction.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SchedulingActionUpsertBulk) Ignore() *SchedulingActionUpsertBulk { + 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 *SchedulingActionUpsertBulk) DoNothing() *SchedulingActionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SchedulingActionCreateBulk.OnConflict +// documentation for more info. +func (u *SchedulingActionUpsertBulk) Update(set func(*SchedulingActionUpsert)) *SchedulingActionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SchedulingActionUpsert{UpdateSet: update}) + })) + return u +} + +// SetPolicyID sets the "policy_id" field. +func (u *SchedulingActionUpsertBulk) SetPolicyID(v int64) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetPolicyID(v) + }) +} + +// AddPolicyID adds v to the "policy_id" field. +func (u *SchedulingActionUpsertBulk) AddPolicyID(v int64) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.AddPolicyID(v) + }) +} + +// UpdatePolicyID sets the "policy_id" field to the value that was provided on create. +func (u *SchedulingActionUpsertBulk) UpdatePolicyID() *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdatePolicyID() + }) +} + +// SetAccountID sets the "account_id" field. +func (u *SchedulingActionUpsertBulk) SetAccountID(v int64) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetAccountID(v) + }) +} + +// AddAccountID adds v to the "account_id" field. +func (u *SchedulingActionUpsertBulk) AddAccountID(v int64) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.AddAccountID(v) + }) +} + +// UpdateAccountID sets the "account_id" field to the value that was provided on create. +func (u *SchedulingActionUpsertBulk) UpdateAccountID() *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateAccountID() + }) +} + +// SetMonitorID sets the "monitor_id" field. +func (u *SchedulingActionUpsertBulk) SetMonitorID(v int64) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetMonitorID(v) + }) +} + +// AddMonitorID adds v to the "monitor_id" field. +func (u *SchedulingActionUpsertBulk) AddMonitorID(v int64) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.AddMonitorID(v) + }) +} + +// UpdateMonitorID sets the "monitor_id" field to the value that was provided on create. +func (u *SchedulingActionUpsertBulk) UpdateMonitorID() *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateMonitorID() + }) +} + +// SetAction sets the "action" field. +func (u *SchedulingActionUpsertBulk) SetAction(v string) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetAction(v) + }) +} + +// UpdateAction sets the "action" field to the value that was provided on create. +func (u *SchedulingActionUpsertBulk) UpdateAction() *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateAction() + }) +} + +// SetReason sets the "reason" field. +func (u *SchedulingActionUpsertBulk) SetReason(v string) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetReason(v) + }) +} + +// UpdateReason sets the "reason" field to the value that was provided on create. +func (u *SchedulingActionUpsertBulk) UpdateReason() *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateReason() + }) +} + +// SetOriginalPriority sets the "original_priority" field. +func (u *SchedulingActionUpsertBulk) SetOriginalPriority(v int) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetOriginalPriority(v) + }) +} + +// AddOriginalPriority adds v to the "original_priority" field. +func (u *SchedulingActionUpsertBulk) AddOriginalPriority(v int) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.AddOriginalPriority(v) + }) +} + +// UpdateOriginalPriority sets the "original_priority" field to the value that was provided on create. +func (u *SchedulingActionUpsertBulk) UpdateOriginalPriority() *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateOriginalPriority() + }) +} + +// SetRestored sets the "restored" field. +func (u *SchedulingActionUpsertBulk) SetRestored(v bool) *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.SetRestored(v) + }) +} + +// UpdateRestored sets the "restored" field to the value that was provided on create. +func (u *SchedulingActionUpsertBulk) UpdateRestored() *SchedulingActionUpsertBulk { + return u.Update(func(s *SchedulingActionUpsert) { + s.UpdateRestored() + }) +} + +// Exec executes the query. +func (u *SchedulingActionUpsertBulk) 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("ent: OnConflict was set for builder %d. Set it on the SchedulingActionCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for SchedulingActionCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SchedulingActionUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/ent/schedulingaction_delete.go b/backend/ent/schedulingaction_delete.go new file mode 100644 index 000000000000..48d41086bdeb --- /dev/null +++ b/backend/ent/schedulingaction_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/Wei-Shaw/sub2api/ent/predicate" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" +) + +// SchedulingActionDelete is the builder for deleting a SchedulingAction entity. +type SchedulingActionDelete struct { + config + hooks []Hook + mutation *SchedulingActionMutation +} + +// Where appends a list predicates to the SchedulingActionDelete builder. +func (_d *SchedulingActionDelete) Where(ps ...predicate.SchedulingAction) *SchedulingActionDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *SchedulingActionDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SchedulingActionDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *SchedulingActionDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(schedulingaction.Table, sqlgraph.NewFieldSpec(schedulingaction.FieldID, field.TypeInt64)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// SchedulingActionDeleteOne is the builder for deleting a single SchedulingAction entity. +type SchedulingActionDeleteOne struct { + _d *SchedulingActionDelete +} + +// Where appends a list predicates to the SchedulingActionDelete builder. +func (_d *SchedulingActionDeleteOne) Where(ps ...predicate.SchedulingAction) *SchedulingActionDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *SchedulingActionDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{schedulingaction.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SchedulingActionDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/ent/schedulingaction_query.go b/backend/ent/schedulingaction_query.go new file mode 100644 index 000000000000..e4d2e2ce4c89 --- /dev/null +++ b/backend/ent/schedulingaction_query.go @@ -0,0 +1,564 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/Wei-Shaw/sub2api/ent/predicate" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" +) + +// SchedulingActionQuery is the builder for querying SchedulingAction entities. +type SchedulingActionQuery struct { + config + ctx *QueryContext + order []schedulingaction.OrderOption + inters []Interceptor + predicates []predicate.SchedulingAction + 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 SchedulingActionQuery builder. +func (_q *SchedulingActionQuery) Where(ps ...predicate.SchedulingAction) *SchedulingActionQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *SchedulingActionQuery) Limit(limit int) *SchedulingActionQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *SchedulingActionQuery) Offset(offset int) *SchedulingActionQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *SchedulingActionQuery) Unique(unique bool) *SchedulingActionQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *SchedulingActionQuery) Order(o ...schedulingaction.OrderOption) *SchedulingActionQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first SchedulingAction entity from the query. +// Returns a *NotFoundError when no SchedulingAction was found. +func (_q *SchedulingActionQuery) First(ctx context.Context) (*SchedulingAction, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{schedulingaction.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *SchedulingActionQuery) FirstX(ctx context.Context) *SchedulingAction { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first SchedulingAction ID from the query. +// Returns a *NotFoundError when no SchedulingAction ID was found. +func (_q *SchedulingActionQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{schedulingaction.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *SchedulingActionQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single SchedulingAction entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one SchedulingAction entity is found. +// Returns a *NotFoundError when no SchedulingAction entities are found. +func (_q *SchedulingActionQuery) Only(ctx context.Context) (*SchedulingAction, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{schedulingaction.Label} + default: + return nil, &NotSingularError{schedulingaction.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *SchedulingActionQuery) OnlyX(ctx context.Context) *SchedulingAction { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only SchedulingAction ID in the query. +// Returns a *NotSingularError when more than one SchedulingAction ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *SchedulingActionQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{schedulingaction.Label} + default: + err = &NotSingularError{schedulingaction.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *SchedulingActionQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of SchedulingActions. +func (_q *SchedulingActionQuery) All(ctx context.Context) ([]*SchedulingAction, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*SchedulingAction, *SchedulingActionQuery]() + return withInterceptors[[]*SchedulingAction](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *SchedulingActionQuery) AllX(ctx context.Context) []*SchedulingAction { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of SchedulingAction IDs. +func (_q *SchedulingActionQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(schedulingaction.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *SchedulingActionQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *SchedulingActionQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*SchedulingActionQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *SchedulingActionQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *SchedulingActionQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *SchedulingActionQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the SchedulingActionQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *SchedulingActionQuery) Clone() *SchedulingActionQuery { + if _q == nil { + return nil + } + return &SchedulingActionQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]schedulingaction.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.SchedulingAction{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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 { +// PolicyID int64 `json:"policy_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.SchedulingAction.Query(). +// GroupBy(schedulingaction.FieldPolicyID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *SchedulingActionQuery) GroupBy(field string, fields ...string) *SchedulingActionGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &SchedulingActionGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = schedulingaction.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 { +// PolicyID int64 `json:"policy_id,omitempty"` +// } +// +// client.SchedulingAction.Query(). +// Select(schedulingaction.FieldPolicyID). +// Scan(ctx, &v) +func (_q *SchedulingActionQuery) Select(fields ...string) *SchedulingActionSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &SchedulingActionSelect{SchedulingActionQuery: _q} + sbuild.label = schedulingaction.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a SchedulingActionSelect configured with the given aggregations. +func (_q *SchedulingActionQuery) Aggregate(fns ...AggregateFunc) *SchedulingActionSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *SchedulingActionQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !schedulingaction.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *SchedulingActionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SchedulingAction, error) { + var ( + nodes = []*SchedulingAction{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*SchedulingAction).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &SchedulingAction{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *SchedulingActionQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *SchedulingActionQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(schedulingaction.Table, schedulingaction.Columns, sqlgraph.NewFieldSpec(schedulingaction.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, schedulingaction.FieldID) + for i := range fields { + if fields[i] != schedulingaction.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *SchedulingActionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(schedulingaction.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = schedulingaction.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *SchedulingActionQuery) ForUpdate(opts ...sql.LockOption) *SchedulingActionQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *SchedulingActionQuery) ForShare(opts ...sql.LockOption) *SchedulingActionQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// SchedulingActionGroupBy is the group-by builder for SchedulingAction entities. +type SchedulingActionGroupBy struct { + selector + build *SchedulingActionQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *SchedulingActionGroupBy) Aggregate(fns ...AggregateFunc) *SchedulingActionGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *SchedulingActionGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SchedulingActionQuery, *SchedulingActionGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *SchedulingActionGroupBy) sqlScan(ctx context.Context, root *SchedulingActionQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// SchedulingActionSelect is the builder for selecting fields of SchedulingAction entities. +type SchedulingActionSelect struct { + *SchedulingActionQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *SchedulingActionSelect) Aggregate(fns ...AggregateFunc) *SchedulingActionSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *SchedulingActionSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SchedulingActionQuery, *SchedulingActionSelect](ctx, _s.SchedulingActionQuery, _s, _s.inters, v) +} + +func (_s *SchedulingActionSelect) sqlScan(ctx context.Context, root *SchedulingActionQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/backend/ent/schedulingaction_update.go b/backend/ent/schedulingaction_update.go new file mode 100644 index 000000000000..97579a940f7b --- /dev/null +++ b/backend/ent/schedulingaction_update.go @@ -0,0 +1,529 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/Wei-Shaw/sub2api/ent/predicate" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" +) + +// SchedulingActionUpdate is the builder for updating SchedulingAction entities. +type SchedulingActionUpdate struct { + config + hooks []Hook + mutation *SchedulingActionMutation +} + +// Where appends a list predicates to the SchedulingActionUpdate builder. +func (_u *SchedulingActionUpdate) Where(ps ...predicate.SchedulingAction) *SchedulingActionUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetPolicyID sets the "policy_id" field. +func (_u *SchedulingActionUpdate) SetPolicyID(v int64) *SchedulingActionUpdate { + _u.mutation.ResetPolicyID() + _u.mutation.SetPolicyID(v) + return _u +} + +// SetNillablePolicyID sets the "policy_id" field if the given value is not nil. +func (_u *SchedulingActionUpdate) SetNillablePolicyID(v *int64) *SchedulingActionUpdate { + if v != nil { + _u.SetPolicyID(*v) + } + return _u +} + +// AddPolicyID adds value to the "policy_id" field. +func (_u *SchedulingActionUpdate) AddPolicyID(v int64) *SchedulingActionUpdate { + _u.mutation.AddPolicyID(v) + return _u +} + +// SetAccountID sets the "account_id" field. +func (_u *SchedulingActionUpdate) SetAccountID(v int64) *SchedulingActionUpdate { + _u.mutation.ResetAccountID() + _u.mutation.SetAccountID(v) + return _u +} + +// SetNillableAccountID sets the "account_id" field if the given value is not nil. +func (_u *SchedulingActionUpdate) SetNillableAccountID(v *int64) *SchedulingActionUpdate { + if v != nil { + _u.SetAccountID(*v) + } + return _u +} + +// AddAccountID adds value to the "account_id" field. +func (_u *SchedulingActionUpdate) AddAccountID(v int64) *SchedulingActionUpdate { + _u.mutation.AddAccountID(v) + return _u +} + +// SetMonitorID sets the "monitor_id" field. +func (_u *SchedulingActionUpdate) SetMonitorID(v int64) *SchedulingActionUpdate { + _u.mutation.ResetMonitorID() + _u.mutation.SetMonitorID(v) + return _u +} + +// SetNillableMonitorID sets the "monitor_id" field if the given value is not nil. +func (_u *SchedulingActionUpdate) SetNillableMonitorID(v *int64) *SchedulingActionUpdate { + if v != nil { + _u.SetMonitorID(*v) + } + return _u +} + +// AddMonitorID adds value to the "monitor_id" field. +func (_u *SchedulingActionUpdate) AddMonitorID(v int64) *SchedulingActionUpdate { + _u.mutation.AddMonitorID(v) + return _u +} + +// SetAction sets the "action" field. +func (_u *SchedulingActionUpdate) SetAction(v string) *SchedulingActionUpdate { + _u.mutation.SetAction(v) + return _u +} + +// SetNillableAction sets the "action" field if the given value is not nil. +func (_u *SchedulingActionUpdate) SetNillableAction(v *string) *SchedulingActionUpdate { + if v != nil { + _u.SetAction(*v) + } + return _u +} + +// SetReason sets the "reason" field. +func (_u *SchedulingActionUpdate) SetReason(v string) *SchedulingActionUpdate { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *SchedulingActionUpdate) SetNillableReason(v *string) *SchedulingActionUpdate { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// SetOriginalPriority sets the "original_priority" field. +func (_u *SchedulingActionUpdate) SetOriginalPriority(v int) *SchedulingActionUpdate { + _u.mutation.ResetOriginalPriority() + _u.mutation.SetOriginalPriority(v) + return _u +} + +// SetNillableOriginalPriority sets the "original_priority" field if the given value is not nil. +func (_u *SchedulingActionUpdate) SetNillableOriginalPriority(v *int) *SchedulingActionUpdate { + if v != nil { + _u.SetOriginalPriority(*v) + } + return _u +} + +// AddOriginalPriority adds value to the "original_priority" field. +func (_u *SchedulingActionUpdate) AddOriginalPriority(v int) *SchedulingActionUpdate { + _u.mutation.AddOriginalPriority(v) + return _u +} + +// SetRestored sets the "restored" field. +func (_u *SchedulingActionUpdate) SetRestored(v bool) *SchedulingActionUpdate { + _u.mutation.SetRestored(v) + return _u +} + +// SetNillableRestored sets the "restored" field if the given value is not nil. +func (_u *SchedulingActionUpdate) SetNillableRestored(v *bool) *SchedulingActionUpdate { + if v != nil { + _u.SetRestored(*v) + } + return _u +} + +// Mutation returns the SchedulingActionMutation object of the builder. +func (_u *SchedulingActionUpdate) Mutation() *SchedulingActionMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *SchedulingActionUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SchedulingActionUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *SchedulingActionUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SchedulingActionUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SchedulingActionUpdate) check() error { + if v, ok := _u.mutation.Action(); ok { + if err := schedulingaction.ActionValidator(v); err != nil { + return &ValidationError{Name: "action", err: fmt.Errorf(`ent: validator failed for field "SchedulingAction.action": %w`, err)} + } + } + if v, ok := _u.mutation.Reason(); ok { + if err := schedulingaction.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`ent: validator failed for field "SchedulingAction.reason": %w`, err)} + } + } + return nil +} + +func (_u *SchedulingActionUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(schedulingaction.Table, schedulingaction.Columns, sqlgraph.NewFieldSpec(schedulingaction.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.PolicyID(); ok { + _spec.SetField(schedulingaction.FieldPolicyID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedPolicyID(); ok { + _spec.AddField(schedulingaction.FieldPolicyID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AccountID(); ok { + _spec.SetField(schedulingaction.FieldAccountID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedAccountID(); ok { + _spec.AddField(schedulingaction.FieldAccountID, field.TypeInt64, value) + } + if value, ok := _u.mutation.MonitorID(); ok { + _spec.SetField(schedulingaction.FieldMonitorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedMonitorID(); ok { + _spec.AddField(schedulingaction.FieldMonitorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.Action(); ok { + _spec.SetField(schedulingaction.FieldAction, field.TypeString, value) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(schedulingaction.FieldReason, field.TypeString, value) + } + if value, ok := _u.mutation.OriginalPriority(); ok { + _spec.SetField(schedulingaction.FieldOriginalPriority, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedOriginalPriority(); ok { + _spec.AddField(schedulingaction.FieldOriginalPriority, field.TypeInt, value) + } + if value, ok := _u.mutation.Restored(); ok { + _spec.SetField(schedulingaction.FieldRestored, field.TypeBool, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{schedulingaction.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// SchedulingActionUpdateOne is the builder for updating a single SchedulingAction entity. +type SchedulingActionUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SchedulingActionMutation +} + +// SetPolicyID sets the "policy_id" field. +func (_u *SchedulingActionUpdateOne) SetPolicyID(v int64) *SchedulingActionUpdateOne { + _u.mutation.ResetPolicyID() + _u.mutation.SetPolicyID(v) + return _u +} + +// SetNillablePolicyID sets the "policy_id" field if the given value is not nil. +func (_u *SchedulingActionUpdateOne) SetNillablePolicyID(v *int64) *SchedulingActionUpdateOne { + if v != nil { + _u.SetPolicyID(*v) + } + return _u +} + +// AddPolicyID adds value to the "policy_id" field. +func (_u *SchedulingActionUpdateOne) AddPolicyID(v int64) *SchedulingActionUpdateOne { + _u.mutation.AddPolicyID(v) + return _u +} + +// SetAccountID sets the "account_id" field. +func (_u *SchedulingActionUpdateOne) SetAccountID(v int64) *SchedulingActionUpdateOne { + _u.mutation.ResetAccountID() + _u.mutation.SetAccountID(v) + return _u +} + +// SetNillableAccountID sets the "account_id" field if the given value is not nil. +func (_u *SchedulingActionUpdateOne) SetNillableAccountID(v *int64) *SchedulingActionUpdateOne { + if v != nil { + _u.SetAccountID(*v) + } + return _u +} + +// AddAccountID adds value to the "account_id" field. +func (_u *SchedulingActionUpdateOne) AddAccountID(v int64) *SchedulingActionUpdateOne { + _u.mutation.AddAccountID(v) + return _u +} + +// SetMonitorID sets the "monitor_id" field. +func (_u *SchedulingActionUpdateOne) SetMonitorID(v int64) *SchedulingActionUpdateOne { + _u.mutation.ResetMonitorID() + _u.mutation.SetMonitorID(v) + return _u +} + +// SetNillableMonitorID sets the "monitor_id" field if the given value is not nil. +func (_u *SchedulingActionUpdateOne) SetNillableMonitorID(v *int64) *SchedulingActionUpdateOne { + if v != nil { + _u.SetMonitorID(*v) + } + return _u +} + +// AddMonitorID adds value to the "monitor_id" field. +func (_u *SchedulingActionUpdateOne) AddMonitorID(v int64) *SchedulingActionUpdateOne { + _u.mutation.AddMonitorID(v) + return _u +} + +// SetAction sets the "action" field. +func (_u *SchedulingActionUpdateOne) SetAction(v string) *SchedulingActionUpdateOne { + _u.mutation.SetAction(v) + return _u +} + +// SetNillableAction sets the "action" field if the given value is not nil. +func (_u *SchedulingActionUpdateOne) SetNillableAction(v *string) *SchedulingActionUpdateOne { + if v != nil { + _u.SetAction(*v) + } + return _u +} + +// SetReason sets the "reason" field. +func (_u *SchedulingActionUpdateOne) SetReason(v string) *SchedulingActionUpdateOne { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *SchedulingActionUpdateOne) SetNillableReason(v *string) *SchedulingActionUpdateOne { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// SetOriginalPriority sets the "original_priority" field. +func (_u *SchedulingActionUpdateOne) SetOriginalPriority(v int) *SchedulingActionUpdateOne { + _u.mutation.ResetOriginalPriority() + _u.mutation.SetOriginalPriority(v) + return _u +} + +// SetNillableOriginalPriority sets the "original_priority" field if the given value is not nil. +func (_u *SchedulingActionUpdateOne) SetNillableOriginalPriority(v *int) *SchedulingActionUpdateOne { + if v != nil { + _u.SetOriginalPriority(*v) + } + return _u +} + +// AddOriginalPriority adds value to the "original_priority" field. +func (_u *SchedulingActionUpdateOne) AddOriginalPriority(v int) *SchedulingActionUpdateOne { + _u.mutation.AddOriginalPriority(v) + return _u +} + +// SetRestored sets the "restored" field. +func (_u *SchedulingActionUpdateOne) SetRestored(v bool) *SchedulingActionUpdateOne { + _u.mutation.SetRestored(v) + return _u +} + +// SetNillableRestored sets the "restored" field if the given value is not nil. +func (_u *SchedulingActionUpdateOne) SetNillableRestored(v *bool) *SchedulingActionUpdateOne { + if v != nil { + _u.SetRestored(*v) + } + return _u +} + +// Mutation returns the SchedulingActionMutation object of the builder. +func (_u *SchedulingActionUpdateOne) Mutation() *SchedulingActionMutation { + return _u.mutation +} + +// Where appends a list predicates to the SchedulingActionUpdate builder. +func (_u *SchedulingActionUpdateOne) Where(ps ...predicate.SchedulingAction) *SchedulingActionUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *SchedulingActionUpdateOne) Select(field string, fields ...string) *SchedulingActionUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated SchedulingAction entity. +func (_u *SchedulingActionUpdateOne) Save(ctx context.Context) (*SchedulingAction, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SchedulingActionUpdateOne) SaveX(ctx context.Context) *SchedulingAction { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *SchedulingActionUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SchedulingActionUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SchedulingActionUpdateOne) check() error { + if v, ok := _u.mutation.Action(); ok { + if err := schedulingaction.ActionValidator(v); err != nil { + return &ValidationError{Name: "action", err: fmt.Errorf(`ent: validator failed for field "SchedulingAction.action": %w`, err)} + } + } + if v, ok := _u.mutation.Reason(); ok { + if err := schedulingaction.ReasonValidator(v); err != nil { + return &ValidationError{Name: "reason", err: fmt.Errorf(`ent: validator failed for field "SchedulingAction.reason": %w`, err)} + } + } + return nil +} + +func (_u *SchedulingActionUpdateOne) sqlSave(ctx context.Context) (_node *SchedulingAction, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(schedulingaction.Table, schedulingaction.Columns, sqlgraph.NewFieldSpec(schedulingaction.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "SchedulingAction.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, schedulingaction.FieldID) + for _, f := range fields { + if !schedulingaction.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != schedulingaction.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.PolicyID(); ok { + _spec.SetField(schedulingaction.FieldPolicyID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedPolicyID(); ok { + _spec.AddField(schedulingaction.FieldPolicyID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AccountID(); ok { + _spec.SetField(schedulingaction.FieldAccountID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedAccountID(); ok { + _spec.AddField(schedulingaction.FieldAccountID, field.TypeInt64, value) + } + if value, ok := _u.mutation.MonitorID(); ok { + _spec.SetField(schedulingaction.FieldMonitorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedMonitorID(); ok { + _spec.AddField(schedulingaction.FieldMonitorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.Action(); ok { + _spec.SetField(schedulingaction.FieldAction, field.TypeString, value) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(schedulingaction.FieldReason, field.TypeString, value) + } + if value, ok := _u.mutation.OriginalPriority(); ok { + _spec.SetField(schedulingaction.FieldOriginalPriority, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedOriginalPriority(); ok { + _spec.AddField(schedulingaction.FieldOriginalPriority, field.TypeInt, value) + } + if value, ok := _u.mutation.Restored(); ok { + _spec.SetField(schedulingaction.FieldRestored, field.TypeBool, value) + } + _node = &SchedulingAction{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{schedulingaction.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/ent/schedulingpolicy.go b/backend/ent/schedulingpolicy.go new file mode 100644 index 000000000000..613f9a886d29 --- /dev/null +++ b/backend/ent/schedulingpolicy.go @@ -0,0 +1,245 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" +) + +// SchedulingPolicy is the model entity for the SchedulingPolicy schema. +type SchedulingPolicy struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Enabled holds the value of the "enabled" field. + Enabled bool `json:"enabled,omitempty"` + // 条件源:channel_monitors.id,监控被删除时策略停摆但保留配置 + MonitorID int64 `json:"monitor_id,omitempty"` + // 动作目标账号 ID 列表 + AccountIds []int64 `json:"account_ids,omitempty"` + // 连续失败 N 次后触发(failed/error 或延迟超阈值均计为失败) + TriggerConsecutiveFailures int `json:"trigger_consecutive_failures,omitempty"` + // 延迟阈值(毫秒),检测延迟超过该值计为一次失败;0 表示不启用延迟条件 + TriggerLatencyMs int `json:"trigger_latency_ms,omitempty"` + // 触发动作:pause(临时停用)或 deprioritize(降低优先级) + ActionType string `json:"action_type,omitempty"` + // pause 动作的停用时长(分钟);0 表示停用至恢复条件满足 + PauseMinutes int `json:"pause_minutes,omitempty"` + // deprioritize 动作在原优先级上增加的数值(数值越大优先级越低) + PriorityDelta int `json:"priority_delta,omitempty"` + // 连续成功 N 次后自动恢复;0 表示不自动恢复 + RecoverConsecutiveSuccesses int `json:"recover_consecutive_successes,omitempty"` + // 两次触发之间的最小间隔(分钟),防止抖动反复触发 + CooldownMinutes int `json:"cooldown_minutes,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*SchedulingPolicy) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case schedulingpolicy.FieldAccountIds: + values[i] = new([]byte) + case schedulingpolicy.FieldEnabled: + values[i] = new(sql.NullBool) + case schedulingpolicy.FieldID, schedulingpolicy.FieldMonitorID, schedulingpolicy.FieldTriggerConsecutiveFailures, schedulingpolicy.FieldTriggerLatencyMs, schedulingpolicy.FieldPauseMinutes, schedulingpolicy.FieldPriorityDelta, schedulingpolicy.FieldRecoverConsecutiveSuccesses, schedulingpolicy.FieldCooldownMinutes: + values[i] = new(sql.NullInt64) + case schedulingpolicy.FieldName, schedulingpolicy.FieldActionType: + values[i] = new(sql.NullString) + case schedulingpolicy.FieldCreatedAt, schedulingpolicy.FieldUpdatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the SchedulingPolicy fields. +func (_m *SchedulingPolicy) 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 schedulingpolicy.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case schedulingpolicy.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case schedulingpolicy.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + case schedulingpolicy.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case schedulingpolicy.FieldEnabled: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field enabled", values[i]) + } else if value.Valid { + _m.Enabled = value.Bool + } + case schedulingpolicy.FieldMonitorID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field monitor_id", values[i]) + } else if value.Valid { + _m.MonitorID = value.Int64 + } + case schedulingpolicy.FieldAccountIds: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field account_ids", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.AccountIds); err != nil { + return fmt.Errorf("unmarshal field account_ids: %w", err) + } + } + case schedulingpolicy.FieldTriggerConsecutiveFailures: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field trigger_consecutive_failures", values[i]) + } else if value.Valid { + _m.TriggerConsecutiveFailures = int(value.Int64) + } + case schedulingpolicy.FieldTriggerLatencyMs: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field trigger_latency_ms", values[i]) + } else if value.Valid { + _m.TriggerLatencyMs = int(value.Int64) + } + case schedulingpolicy.FieldActionType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field action_type", values[i]) + } else if value.Valid { + _m.ActionType = value.String + } + case schedulingpolicy.FieldPauseMinutes: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field pause_minutes", values[i]) + } else if value.Valid { + _m.PauseMinutes = int(value.Int64) + } + case schedulingpolicy.FieldPriorityDelta: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field priority_delta", values[i]) + } else if value.Valid { + _m.PriorityDelta = int(value.Int64) + } + case schedulingpolicy.FieldRecoverConsecutiveSuccesses: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field recover_consecutive_successes", values[i]) + } else if value.Valid { + _m.RecoverConsecutiveSuccesses = int(value.Int64) + } + case schedulingpolicy.FieldCooldownMinutes: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field cooldown_minutes", values[i]) + } else if value.Valid { + _m.CooldownMinutes = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the SchedulingPolicy. +// This includes values selected through modifiers, order, etc. +func (_m *SchedulingPolicy) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this SchedulingPolicy. +// Note that you need to call SchedulingPolicy.Unwrap() before calling this method if this SchedulingPolicy +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *SchedulingPolicy) Update() *SchedulingPolicyUpdateOne { + return NewSchedulingPolicyClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the SchedulingPolicy 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 (_m *SchedulingPolicy) Unwrap() *SchedulingPolicy { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: SchedulingPolicy is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *SchedulingPolicy) String() string { + var builder strings.Builder + builder.WriteString("SchedulingPolicy(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("enabled=") + builder.WriteString(fmt.Sprintf("%v", _m.Enabled)) + builder.WriteString(", ") + builder.WriteString("monitor_id=") + builder.WriteString(fmt.Sprintf("%v", _m.MonitorID)) + builder.WriteString(", ") + builder.WriteString("account_ids=") + builder.WriteString(fmt.Sprintf("%v", _m.AccountIds)) + builder.WriteString(", ") + builder.WriteString("trigger_consecutive_failures=") + builder.WriteString(fmt.Sprintf("%v", _m.TriggerConsecutiveFailures)) + builder.WriteString(", ") + builder.WriteString("trigger_latency_ms=") + builder.WriteString(fmt.Sprintf("%v", _m.TriggerLatencyMs)) + builder.WriteString(", ") + builder.WriteString("action_type=") + builder.WriteString(_m.ActionType) + builder.WriteString(", ") + builder.WriteString("pause_minutes=") + builder.WriteString(fmt.Sprintf("%v", _m.PauseMinutes)) + builder.WriteString(", ") + builder.WriteString("priority_delta=") + builder.WriteString(fmt.Sprintf("%v", _m.PriorityDelta)) + builder.WriteString(", ") + builder.WriteString("recover_consecutive_successes=") + builder.WriteString(fmt.Sprintf("%v", _m.RecoverConsecutiveSuccesses)) + builder.WriteString(", ") + builder.WriteString("cooldown_minutes=") + builder.WriteString(fmt.Sprintf("%v", _m.CooldownMinutes)) + builder.WriteByte(')') + return builder.String() +} + +// SchedulingPolicies is a parsable slice of SchedulingPolicy. +type SchedulingPolicies []*SchedulingPolicy diff --git a/backend/ent/schedulingpolicy/schedulingpolicy.go b/backend/ent/schedulingpolicy/schedulingpolicy.go new file mode 100644 index 000000000000..2394f55bbb0b --- /dev/null +++ b/backend/ent/schedulingpolicy/schedulingpolicy.go @@ -0,0 +1,183 @@ +// Code generated by ent, DO NOT EDIT. + +package schedulingpolicy + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the schedulingpolicy type in the database. + Label = "scheduling_policy" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldEnabled holds the string denoting the enabled field in the database. + FieldEnabled = "enabled" + // FieldMonitorID holds the string denoting the monitor_id field in the database. + FieldMonitorID = "monitor_id" + // FieldAccountIds holds the string denoting the account_ids field in the database. + FieldAccountIds = "account_ids" + // FieldTriggerConsecutiveFailures holds the string denoting the trigger_consecutive_failures field in the database. + FieldTriggerConsecutiveFailures = "trigger_consecutive_failures" + // FieldTriggerLatencyMs holds the string denoting the trigger_latency_ms field in the database. + FieldTriggerLatencyMs = "trigger_latency_ms" + // FieldActionType holds the string denoting the action_type field in the database. + FieldActionType = "action_type" + // FieldPauseMinutes holds the string denoting the pause_minutes field in the database. + FieldPauseMinutes = "pause_minutes" + // FieldPriorityDelta holds the string denoting the priority_delta field in the database. + FieldPriorityDelta = "priority_delta" + // FieldRecoverConsecutiveSuccesses holds the string denoting the recover_consecutive_successes field in the database. + FieldRecoverConsecutiveSuccesses = "recover_consecutive_successes" + // FieldCooldownMinutes holds the string denoting the cooldown_minutes field in the database. + FieldCooldownMinutes = "cooldown_minutes" + // Table holds the table name of the schedulingpolicy in the database. + Table = "scheduling_policies" +) + +// Columns holds all SQL columns for schedulingpolicy fields. +var Columns = []string{ + FieldID, + FieldCreatedAt, + FieldUpdatedAt, + FieldName, + FieldEnabled, + FieldMonitorID, + FieldAccountIds, + FieldTriggerConsecutiveFailures, + FieldTriggerLatencyMs, + FieldActionType, + FieldPauseMinutes, + FieldPriorityDelta, + FieldRecoverConsecutiveSuccesses, + FieldCooldownMinutes, +} + +// 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 +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // DefaultEnabled holds the default value on creation for the "enabled" field. + DefaultEnabled bool + // DefaultAccountIds holds the default value on creation for the "account_ids" field. + DefaultAccountIds []int64 + // DefaultTriggerConsecutiveFailures holds the default value on creation for the "trigger_consecutive_failures" field. + DefaultTriggerConsecutiveFailures int + // TriggerConsecutiveFailuresValidator is a validator for the "trigger_consecutive_failures" field. It is called by the builders before save. + TriggerConsecutiveFailuresValidator func(int) error + // DefaultTriggerLatencyMs holds the default value on creation for the "trigger_latency_ms" field. + DefaultTriggerLatencyMs int + // TriggerLatencyMsValidator is a validator for the "trigger_latency_ms" field. It is called by the builders before save. + TriggerLatencyMsValidator func(int) error + // DefaultActionType holds the default value on creation for the "action_type" field. + DefaultActionType string + // ActionTypeValidator is a validator for the "action_type" field. It is called by the builders before save. + ActionTypeValidator func(string) error + // DefaultPauseMinutes holds the default value on creation for the "pause_minutes" field. + DefaultPauseMinutes int + // PauseMinutesValidator is a validator for the "pause_minutes" field. It is called by the builders before save. + PauseMinutesValidator func(int) error + // DefaultPriorityDelta holds the default value on creation for the "priority_delta" field. + DefaultPriorityDelta int + // PriorityDeltaValidator is a validator for the "priority_delta" field. It is called by the builders before save. + PriorityDeltaValidator func(int) error + // DefaultRecoverConsecutiveSuccesses holds the default value on creation for the "recover_consecutive_successes" field. + DefaultRecoverConsecutiveSuccesses int + // RecoverConsecutiveSuccessesValidator is a validator for the "recover_consecutive_successes" field. It is called by the builders before save. + RecoverConsecutiveSuccessesValidator func(int) error + // DefaultCooldownMinutes holds the default value on creation for the "cooldown_minutes" field. + DefaultCooldownMinutes int + // CooldownMinutesValidator is a validator for the "cooldown_minutes" field. It is called by the builders before save. + CooldownMinutesValidator func(int) error +) + +// OrderOption defines the ordering options for the SchedulingPolicy 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() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByEnabled orders the results by the enabled field. +func ByEnabled(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEnabled, opts...).ToFunc() +} + +// ByMonitorID orders the results by the monitor_id field. +func ByMonitorID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMonitorID, opts...).ToFunc() +} + +// ByTriggerConsecutiveFailures orders the results by the trigger_consecutive_failures field. +func ByTriggerConsecutiveFailures(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTriggerConsecutiveFailures, opts...).ToFunc() +} + +// ByTriggerLatencyMs orders the results by the trigger_latency_ms field. +func ByTriggerLatencyMs(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTriggerLatencyMs, opts...).ToFunc() +} + +// ByActionType orders the results by the action_type field. +func ByActionType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldActionType, opts...).ToFunc() +} + +// ByPauseMinutes orders the results by the pause_minutes field. +func ByPauseMinutes(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPauseMinutes, opts...).ToFunc() +} + +// ByPriorityDelta orders the results by the priority_delta field. +func ByPriorityDelta(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPriorityDelta, opts...).ToFunc() +} + +// ByRecoverConsecutiveSuccesses orders the results by the recover_consecutive_successes field. +func ByRecoverConsecutiveSuccesses(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRecoverConsecutiveSuccesses, opts...).ToFunc() +} + +// ByCooldownMinutes orders the results by the cooldown_minutes field. +func ByCooldownMinutes(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCooldownMinutes, opts...).ToFunc() +} diff --git a/backend/ent/schedulingpolicy/where.go b/backend/ent/schedulingpolicy/where.go new file mode 100644 index 000000000000..947b2f1f859f --- /dev/null +++ b/backend/ent/schedulingpolicy/where.go @@ -0,0 +1,630 @@ +// Code generated by ent, DO NOT EDIT. + +package schedulingpolicy + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "github.com/Wei-Shaw/sub2api/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldID, id)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldName, v)) +} + +// Enabled applies equality check predicate on the "enabled" field. It's identical to EnabledEQ. +func Enabled(v bool) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldEnabled, v)) +} + +// MonitorID applies equality check predicate on the "monitor_id" field. It's identical to MonitorIDEQ. +func MonitorID(v int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldMonitorID, v)) +} + +// TriggerConsecutiveFailures applies equality check predicate on the "trigger_consecutive_failures" field. It's identical to TriggerConsecutiveFailuresEQ. +func TriggerConsecutiveFailures(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldTriggerConsecutiveFailures, v)) +} + +// TriggerLatencyMs applies equality check predicate on the "trigger_latency_ms" field. It's identical to TriggerLatencyMsEQ. +func TriggerLatencyMs(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldTriggerLatencyMs, v)) +} + +// ActionType applies equality check predicate on the "action_type" field. It's identical to ActionTypeEQ. +func ActionType(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldActionType, v)) +} + +// PauseMinutes applies equality check predicate on the "pause_minutes" field. It's identical to PauseMinutesEQ. +func PauseMinutes(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldPauseMinutes, v)) +} + +// PriorityDelta applies equality check predicate on the "priority_delta" field. It's identical to PriorityDeltaEQ. +func PriorityDelta(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldPriorityDelta, v)) +} + +// RecoverConsecutiveSuccesses applies equality check predicate on the "recover_consecutive_successes" field. It's identical to RecoverConsecutiveSuccessesEQ. +func RecoverConsecutiveSuccesses(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldRecoverConsecutiveSuccesses, v)) +} + +// CooldownMinutes applies equality check predicate on the "cooldown_minutes" field. It's identical to CooldownMinutesEQ. +func CooldownMinutes(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldCooldownMinutes, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldContainsFold(FieldName, v)) +} + +// EnabledEQ applies the EQ predicate on the "enabled" field. +func EnabledEQ(v bool) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldEnabled, v)) +} + +// EnabledNEQ applies the NEQ predicate on the "enabled" field. +func EnabledNEQ(v bool) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldEnabled, v)) +} + +// MonitorIDEQ applies the EQ predicate on the "monitor_id" field. +func MonitorIDEQ(v int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldMonitorID, v)) +} + +// MonitorIDNEQ applies the NEQ predicate on the "monitor_id" field. +func MonitorIDNEQ(v int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldMonitorID, v)) +} + +// MonitorIDIn applies the In predicate on the "monitor_id" field. +func MonitorIDIn(vs ...int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldMonitorID, vs...)) +} + +// MonitorIDNotIn applies the NotIn predicate on the "monitor_id" field. +func MonitorIDNotIn(vs ...int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldMonitorID, vs...)) +} + +// MonitorIDGT applies the GT predicate on the "monitor_id" field. +func MonitorIDGT(v int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldMonitorID, v)) +} + +// MonitorIDGTE applies the GTE predicate on the "monitor_id" field. +func MonitorIDGTE(v int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldMonitorID, v)) +} + +// MonitorIDLT applies the LT predicate on the "monitor_id" field. +func MonitorIDLT(v int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldMonitorID, v)) +} + +// MonitorIDLTE applies the LTE predicate on the "monitor_id" field. +func MonitorIDLTE(v int64) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldMonitorID, v)) +} + +// TriggerConsecutiveFailuresEQ applies the EQ predicate on the "trigger_consecutive_failures" field. +func TriggerConsecutiveFailuresEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldTriggerConsecutiveFailures, v)) +} + +// TriggerConsecutiveFailuresNEQ applies the NEQ predicate on the "trigger_consecutive_failures" field. +func TriggerConsecutiveFailuresNEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldTriggerConsecutiveFailures, v)) +} + +// TriggerConsecutiveFailuresIn applies the In predicate on the "trigger_consecutive_failures" field. +func TriggerConsecutiveFailuresIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldTriggerConsecutiveFailures, vs...)) +} + +// TriggerConsecutiveFailuresNotIn applies the NotIn predicate on the "trigger_consecutive_failures" field. +func TriggerConsecutiveFailuresNotIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldTriggerConsecutiveFailures, vs...)) +} + +// TriggerConsecutiveFailuresGT applies the GT predicate on the "trigger_consecutive_failures" field. +func TriggerConsecutiveFailuresGT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldTriggerConsecutiveFailures, v)) +} + +// TriggerConsecutiveFailuresGTE applies the GTE predicate on the "trigger_consecutive_failures" field. +func TriggerConsecutiveFailuresGTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldTriggerConsecutiveFailures, v)) +} + +// TriggerConsecutiveFailuresLT applies the LT predicate on the "trigger_consecutive_failures" field. +func TriggerConsecutiveFailuresLT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldTriggerConsecutiveFailures, v)) +} + +// TriggerConsecutiveFailuresLTE applies the LTE predicate on the "trigger_consecutive_failures" field. +func TriggerConsecutiveFailuresLTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldTriggerConsecutiveFailures, v)) +} + +// TriggerLatencyMsEQ applies the EQ predicate on the "trigger_latency_ms" field. +func TriggerLatencyMsEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldTriggerLatencyMs, v)) +} + +// TriggerLatencyMsNEQ applies the NEQ predicate on the "trigger_latency_ms" field. +func TriggerLatencyMsNEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldTriggerLatencyMs, v)) +} + +// TriggerLatencyMsIn applies the In predicate on the "trigger_latency_ms" field. +func TriggerLatencyMsIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldTriggerLatencyMs, vs...)) +} + +// TriggerLatencyMsNotIn applies the NotIn predicate on the "trigger_latency_ms" field. +func TriggerLatencyMsNotIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldTriggerLatencyMs, vs...)) +} + +// TriggerLatencyMsGT applies the GT predicate on the "trigger_latency_ms" field. +func TriggerLatencyMsGT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldTriggerLatencyMs, v)) +} + +// TriggerLatencyMsGTE applies the GTE predicate on the "trigger_latency_ms" field. +func TriggerLatencyMsGTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldTriggerLatencyMs, v)) +} + +// TriggerLatencyMsLT applies the LT predicate on the "trigger_latency_ms" field. +func TriggerLatencyMsLT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldTriggerLatencyMs, v)) +} + +// TriggerLatencyMsLTE applies the LTE predicate on the "trigger_latency_ms" field. +func TriggerLatencyMsLTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldTriggerLatencyMs, v)) +} + +// ActionTypeEQ applies the EQ predicate on the "action_type" field. +func ActionTypeEQ(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldActionType, v)) +} + +// ActionTypeNEQ applies the NEQ predicate on the "action_type" field. +func ActionTypeNEQ(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldActionType, v)) +} + +// ActionTypeIn applies the In predicate on the "action_type" field. +func ActionTypeIn(vs ...string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldActionType, vs...)) +} + +// ActionTypeNotIn applies the NotIn predicate on the "action_type" field. +func ActionTypeNotIn(vs ...string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldActionType, vs...)) +} + +// ActionTypeGT applies the GT predicate on the "action_type" field. +func ActionTypeGT(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldActionType, v)) +} + +// ActionTypeGTE applies the GTE predicate on the "action_type" field. +func ActionTypeGTE(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldActionType, v)) +} + +// ActionTypeLT applies the LT predicate on the "action_type" field. +func ActionTypeLT(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldActionType, v)) +} + +// ActionTypeLTE applies the LTE predicate on the "action_type" field. +func ActionTypeLTE(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldActionType, v)) +} + +// ActionTypeContains applies the Contains predicate on the "action_type" field. +func ActionTypeContains(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldContains(FieldActionType, v)) +} + +// ActionTypeHasPrefix applies the HasPrefix predicate on the "action_type" field. +func ActionTypeHasPrefix(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldHasPrefix(FieldActionType, v)) +} + +// ActionTypeHasSuffix applies the HasSuffix predicate on the "action_type" field. +func ActionTypeHasSuffix(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldHasSuffix(FieldActionType, v)) +} + +// ActionTypeEqualFold applies the EqualFold predicate on the "action_type" field. +func ActionTypeEqualFold(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEqualFold(FieldActionType, v)) +} + +// ActionTypeContainsFold applies the ContainsFold predicate on the "action_type" field. +func ActionTypeContainsFold(v string) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldContainsFold(FieldActionType, v)) +} + +// PauseMinutesEQ applies the EQ predicate on the "pause_minutes" field. +func PauseMinutesEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldPauseMinutes, v)) +} + +// PauseMinutesNEQ applies the NEQ predicate on the "pause_minutes" field. +func PauseMinutesNEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldPauseMinutes, v)) +} + +// PauseMinutesIn applies the In predicate on the "pause_minutes" field. +func PauseMinutesIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldPauseMinutes, vs...)) +} + +// PauseMinutesNotIn applies the NotIn predicate on the "pause_minutes" field. +func PauseMinutesNotIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldPauseMinutes, vs...)) +} + +// PauseMinutesGT applies the GT predicate on the "pause_minutes" field. +func PauseMinutesGT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldPauseMinutes, v)) +} + +// PauseMinutesGTE applies the GTE predicate on the "pause_minutes" field. +func PauseMinutesGTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldPauseMinutes, v)) +} + +// PauseMinutesLT applies the LT predicate on the "pause_minutes" field. +func PauseMinutesLT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldPauseMinutes, v)) +} + +// PauseMinutesLTE applies the LTE predicate on the "pause_minutes" field. +func PauseMinutesLTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldPauseMinutes, v)) +} + +// PriorityDeltaEQ applies the EQ predicate on the "priority_delta" field. +func PriorityDeltaEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldPriorityDelta, v)) +} + +// PriorityDeltaNEQ applies the NEQ predicate on the "priority_delta" field. +func PriorityDeltaNEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldPriorityDelta, v)) +} + +// PriorityDeltaIn applies the In predicate on the "priority_delta" field. +func PriorityDeltaIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldPriorityDelta, vs...)) +} + +// PriorityDeltaNotIn applies the NotIn predicate on the "priority_delta" field. +func PriorityDeltaNotIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldPriorityDelta, vs...)) +} + +// PriorityDeltaGT applies the GT predicate on the "priority_delta" field. +func PriorityDeltaGT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldPriorityDelta, v)) +} + +// PriorityDeltaGTE applies the GTE predicate on the "priority_delta" field. +func PriorityDeltaGTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldPriorityDelta, v)) +} + +// PriorityDeltaLT applies the LT predicate on the "priority_delta" field. +func PriorityDeltaLT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldPriorityDelta, v)) +} + +// PriorityDeltaLTE applies the LTE predicate on the "priority_delta" field. +func PriorityDeltaLTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldPriorityDelta, v)) +} + +// RecoverConsecutiveSuccessesEQ applies the EQ predicate on the "recover_consecutive_successes" field. +func RecoverConsecutiveSuccessesEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldRecoverConsecutiveSuccesses, v)) +} + +// RecoverConsecutiveSuccessesNEQ applies the NEQ predicate on the "recover_consecutive_successes" field. +func RecoverConsecutiveSuccessesNEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldRecoverConsecutiveSuccesses, v)) +} + +// RecoverConsecutiveSuccessesIn applies the In predicate on the "recover_consecutive_successes" field. +func RecoverConsecutiveSuccessesIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldRecoverConsecutiveSuccesses, vs...)) +} + +// RecoverConsecutiveSuccessesNotIn applies the NotIn predicate on the "recover_consecutive_successes" field. +func RecoverConsecutiveSuccessesNotIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldRecoverConsecutiveSuccesses, vs...)) +} + +// RecoverConsecutiveSuccessesGT applies the GT predicate on the "recover_consecutive_successes" field. +func RecoverConsecutiveSuccessesGT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldRecoverConsecutiveSuccesses, v)) +} + +// RecoverConsecutiveSuccessesGTE applies the GTE predicate on the "recover_consecutive_successes" field. +func RecoverConsecutiveSuccessesGTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldRecoverConsecutiveSuccesses, v)) +} + +// RecoverConsecutiveSuccessesLT applies the LT predicate on the "recover_consecutive_successes" field. +func RecoverConsecutiveSuccessesLT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldRecoverConsecutiveSuccesses, v)) +} + +// RecoverConsecutiveSuccessesLTE applies the LTE predicate on the "recover_consecutive_successes" field. +func RecoverConsecutiveSuccessesLTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldRecoverConsecutiveSuccesses, v)) +} + +// CooldownMinutesEQ applies the EQ predicate on the "cooldown_minutes" field. +func CooldownMinutesEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldEQ(FieldCooldownMinutes, v)) +} + +// CooldownMinutesNEQ applies the NEQ predicate on the "cooldown_minutes" field. +func CooldownMinutesNEQ(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNEQ(FieldCooldownMinutes, v)) +} + +// CooldownMinutesIn applies the In predicate on the "cooldown_minutes" field. +func CooldownMinutesIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldIn(FieldCooldownMinutes, vs...)) +} + +// CooldownMinutesNotIn applies the NotIn predicate on the "cooldown_minutes" field. +func CooldownMinutesNotIn(vs ...int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldNotIn(FieldCooldownMinutes, vs...)) +} + +// CooldownMinutesGT applies the GT predicate on the "cooldown_minutes" field. +func CooldownMinutesGT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGT(FieldCooldownMinutes, v)) +} + +// CooldownMinutesGTE applies the GTE predicate on the "cooldown_minutes" field. +func CooldownMinutesGTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldGTE(FieldCooldownMinutes, v)) +} + +// CooldownMinutesLT applies the LT predicate on the "cooldown_minutes" field. +func CooldownMinutesLT(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLT(FieldCooldownMinutes, v)) +} + +// CooldownMinutesLTE applies the LTE predicate on the "cooldown_minutes" field. +func CooldownMinutesLTE(v int) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.FieldLTE(FieldCooldownMinutes, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.SchedulingPolicy) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.SchedulingPolicy) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.SchedulingPolicy) predicate.SchedulingPolicy { + return predicate.SchedulingPolicy(sql.NotPredicates(p)) +} diff --git a/backend/ent/schedulingpolicy_create.go b/backend/ent/schedulingpolicy_create.go new file mode 100644 index 000000000000..f9af7c5115e9 --- /dev/null +++ b/backend/ent/schedulingpolicy_create.go @@ -0,0 +1,1373 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" +) + +// SchedulingPolicyCreate is the builder for creating a SchedulingPolicy entity. +type SchedulingPolicyCreate struct { + config + mutation *SchedulingPolicyMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetCreatedAt sets the "created_at" field. +func (_c *SchedulingPolicyCreate) SetCreatedAt(v time.Time) *SchedulingPolicyCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *SchedulingPolicyCreate) SetNillableCreatedAt(v *time.Time) *SchedulingPolicyCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *SchedulingPolicyCreate) SetUpdatedAt(v time.Time) *SchedulingPolicyCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *SchedulingPolicyCreate) SetNillableUpdatedAt(v *time.Time) *SchedulingPolicyCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *SchedulingPolicyCreate) SetName(v string) *SchedulingPolicyCreate { + _c.mutation.SetName(v) + return _c +} + +// SetEnabled sets the "enabled" field. +func (_c *SchedulingPolicyCreate) SetEnabled(v bool) *SchedulingPolicyCreate { + _c.mutation.SetEnabled(v) + return _c +} + +// SetNillableEnabled sets the "enabled" field if the given value is not nil. +func (_c *SchedulingPolicyCreate) SetNillableEnabled(v *bool) *SchedulingPolicyCreate { + if v != nil { + _c.SetEnabled(*v) + } + return _c +} + +// SetMonitorID sets the "monitor_id" field. +func (_c *SchedulingPolicyCreate) SetMonitorID(v int64) *SchedulingPolicyCreate { + _c.mutation.SetMonitorID(v) + return _c +} + +// SetAccountIds sets the "account_ids" field. +func (_c *SchedulingPolicyCreate) SetAccountIds(v []int64) *SchedulingPolicyCreate { + _c.mutation.SetAccountIds(v) + return _c +} + +// SetTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field. +func (_c *SchedulingPolicyCreate) SetTriggerConsecutiveFailures(v int) *SchedulingPolicyCreate { + _c.mutation.SetTriggerConsecutiveFailures(v) + return _c +} + +// SetNillableTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field if the given value is not nil. +func (_c *SchedulingPolicyCreate) SetNillableTriggerConsecutiveFailures(v *int) *SchedulingPolicyCreate { + if v != nil { + _c.SetTriggerConsecutiveFailures(*v) + } + return _c +} + +// SetTriggerLatencyMs sets the "trigger_latency_ms" field. +func (_c *SchedulingPolicyCreate) SetTriggerLatencyMs(v int) *SchedulingPolicyCreate { + _c.mutation.SetTriggerLatencyMs(v) + return _c +} + +// SetNillableTriggerLatencyMs sets the "trigger_latency_ms" field if the given value is not nil. +func (_c *SchedulingPolicyCreate) SetNillableTriggerLatencyMs(v *int) *SchedulingPolicyCreate { + if v != nil { + _c.SetTriggerLatencyMs(*v) + } + return _c +} + +// SetActionType sets the "action_type" field. +func (_c *SchedulingPolicyCreate) SetActionType(v string) *SchedulingPolicyCreate { + _c.mutation.SetActionType(v) + return _c +} + +// SetNillableActionType sets the "action_type" field if the given value is not nil. +func (_c *SchedulingPolicyCreate) SetNillableActionType(v *string) *SchedulingPolicyCreate { + if v != nil { + _c.SetActionType(*v) + } + return _c +} + +// SetPauseMinutes sets the "pause_minutes" field. +func (_c *SchedulingPolicyCreate) SetPauseMinutes(v int) *SchedulingPolicyCreate { + _c.mutation.SetPauseMinutes(v) + return _c +} + +// SetNillablePauseMinutes sets the "pause_minutes" field if the given value is not nil. +func (_c *SchedulingPolicyCreate) SetNillablePauseMinutes(v *int) *SchedulingPolicyCreate { + if v != nil { + _c.SetPauseMinutes(*v) + } + return _c +} + +// SetPriorityDelta sets the "priority_delta" field. +func (_c *SchedulingPolicyCreate) SetPriorityDelta(v int) *SchedulingPolicyCreate { + _c.mutation.SetPriorityDelta(v) + return _c +} + +// SetNillablePriorityDelta sets the "priority_delta" field if the given value is not nil. +func (_c *SchedulingPolicyCreate) SetNillablePriorityDelta(v *int) *SchedulingPolicyCreate { + if v != nil { + _c.SetPriorityDelta(*v) + } + return _c +} + +// SetRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field. +func (_c *SchedulingPolicyCreate) SetRecoverConsecutiveSuccesses(v int) *SchedulingPolicyCreate { + _c.mutation.SetRecoverConsecutiveSuccesses(v) + return _c +} + +// SetNillableRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field if the given value is not nil. +func (_c *SchedulingPolicyCreate) SetNillableRecoverConsecutiveSuccesses(v *int) *SchedulingPolicyCreate { + if v != nil { + _c.SetRecoverConsecutiveSuccesses(*v) + } + return _c +} + +// SetCooldownMinutes sets the "cooldown_minutes" field. +func (_c *SchedulingPolicyCreate) SetCooldownMinutes(v int) *SchedulingPolicyCreate { + _c.mutation.SetCooldownMinutes(v) + return _c +} + +// SetNillableCooldownMinutes sets the "cooldown_minutes" field if the given value is not nil. +func (_c *SchedulingPolicyCreate) SetNillableCooldownMinutes(v *int) *SchedulingPolicyCreate { + if v != nil { + _c.SetCooldownMinutes(*v) + } + return _c +} + +// Mutation returns the SchedulingPolicyMutation object of the builder. +func (_c *SchedulingPolicyCreate) Mutation() *SchedulingPolicyMutation { + return _c.mutation +} + +// Save creates the SchedulingPolicy in the database. +func (_c *SchedulingPolicyCreate) Save(ctx context.Context) (*SchedulingPolicy, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *SchedulingPolicyCreate) SaveX(ctx context.Context) *SchedulingPolicy { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SchedulingPolicyCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SchedulingPolicyCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *SchedulingPolicyCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := schedulingpolicy.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := schedulingpolicy.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.Enabled(); !ok { + v := schedulingpolicy.DefaultEnabled + _c.mutation.SetEnabled(v) + } + if _, ok := _c.mutation.AccountIds(); !ok { + v := schedulingpolicy.DefaultAccountIds + _c.mutation.SetAccountIds(v) + } + if _, ok := _c.mutation.TriggerConsecutiveFailures(); !ok { + v := schedulingpolicy.DefaultTriggerConsecutiveFailures + _c.mutation.SetTriggerConsecutiveFailures(v) + } + if _, ok := _c.mutation.TriggerLatencyMs(); !ok { + v := schedulingpolicy.DefaultTriggerLatencyMs + _c.mutation.SetTriggerLatencyMs(v) + } + if _, ok := _c.mutation.ActionType(); !ok { + v := schedulingpolicy.DefaultActionType + _c.mutation.SetActionType(v) + } + if _, ok := _c.mutation.PauseMinutes(); !ok { + v := schedulingpolicy.DefaultPauseMinutes + _c.mutation.SetPauseMinutes(v) + } + if _, ok := _c.mutation.PriorityDelta(); !ok { + v := schedulingpolicy.DefaultPriorityDelta + _c.mutation.SetPriorityDelta(v) + } + if _, ok := _c.mutation.RecoverConsecutiveSuccesses(); !ok { + v := schedulingpolicy.DefaultRecoverConsecutiveSuccesses + _c.mutation.SetRecoverConsecutiveSuccesses(v) + } + if _, ok := _c.mutation.CooldownMinutes(); !ok { + v := schedulingpolicy.DefaultCooldownMinutes + _c.mutation.SetCooldownMinutes(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *SchedulingPolicyCreate) check() error { + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "SchedulingPolicy.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "SchedulingPolicy.updated_at"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "SchedulingPolicy.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := schedulingpolicy.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.name": %w`, err)} + } + } + if _, ok := _c.mutation.Enabled(); !ok { + return &ValidationError{Name: "enabled", err: errors.New(`ent: missing required field "SchedulingPolicy.enabled"`)} + } + if _, ok := _c.mutation.MonitorID(); !ok { + return &ValidationError{Name: "monitor_id", err: errors.New(`ent: missing required field "SchedulingPolicy.monitor_id"`)} + } + if _, ok := _c.mutation.AccountIds(); !ok { + return &ValidationError{Name: "account_ids", err: errors.New(`ent: missing required field "SchedulingPolicy.account_ids"`)} + } + if _, ok := _c.mutation.TriggerConsecutiveFailures(); !ok { + return &ValidationError{Name: "trigger_consecutive_failures", err: errors.New(`ent: missing required field "SchedulingPolicy.trigger_consecutive_failures"`)} + } + if v, ok := _c.mutation.TriggerConsecutiveFailures(); ok { + if err := schedulingpolicy.TriggerConsecutiveFailuresValidator(v); err != nil { + return &ValidationError{Name: "trigger_consecutive_failures", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.trigger_consecutive_failures": %w`, err)} + } + } + if _, ok := _c.mutation.TriggerLatencyMs(); !ok { + return &ValidationError{Name: "trigger_latency_ms", err: errors.New(`ent: missing required field "SchedulingPolicy.trigger_latency_ms"`)} + } + if v, ok := _c.mutation.TriggerLatencyMs(); ok { + if err := schedulingpolicy.TriggerLatencyMsValidator(v); err != nil { + return &ValidationError{Name: "trigger_latency_ms", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.trigger_latency_ms": %w`, err)} + } + } + if _, ok := _c.mutation.ActionType(); !ok { + return &ValidationError{Name: "action_type", err: errors.New(`ent: missing required field "SchedulingPolicy.action_type"`)} + } + if v, ok := _c.mutation.ActionType(); ok { + if err := schedulingpolicy.ActionTypeValidator(v); err != nil { + return &ValidationError{Name: "action_type", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.action_type": %w`, err)} + } + } + if _, ok := _c.mutation.PauseMinutes(); !ok { + return &ValidationError{Name: "pause_minutes", err: errors.New(`ent: missing required field "SchedulingPolicy.pause_minutes"`)} + } + if v, ok := _c.mutation.PauseMinutes(); ok { + if err := schedulingpolicy.PauseMinutesValidator(v); err != nil { + return &ValidationError{Name: "pause_minutes", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.pause_minutes": %w`, err)} + } + } + if _, ok := _c.mutation.PriorityDelta(); !ok { + return &ValidationError{Name: "priority_delta", err: errors.New(`ent: missing required field "SchedulingPolicy.priority_delta"`)} + } + if v, ok := _c.mutation.PriorityDelta(); ok { + if err := schedulingpolicy.PriorityDeltaValidator(v); err != nil { + return &ValidationError{Name: "priority_delta", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.priority_delta": %w`, err)} + } + } + if _, ok := _c.mutation.RecoverConsecutiveSuccesses(); !ok { + return &ValidationError{Name: "recover_consecutive_successes", err: errors.New(`ent: missing required field "SchedulingPolicy.recover_consecutive_successes"`)} + } + if v, ok := _c.mutation.RecoverConsecutiveSuccesses(); ok { + if err := schedulingpolicy.RecoverConsecutiveSuccessesValidator(v); err != nil { + return &ValidationError{Name: "recover_consecutive_successes", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.recover_consecutive_successes": %w`, err)} + } + } + if _, ok := _c.mutation.CooldownMinutes(); !ok { + return &ValidationError{Name: "cooldown_minutes", err: errors.New(`ent: missing required field "SchedulingPolicy.cooldown_minutes"`)} + } + if v, ok := _c.mutation.CooldownMinutes(); ok { + if err := schedulingpolicy.CooldownMinutesValidator(v); err != nil { + return &ValidationError{Name: "cooldown_minutes", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.cooldown_minutes": %w`, err)} + } + } + return nil +} + +func (_c *SchedulingPolicyCreate) sqlSave(ctx context.Context) (*SchedulingPolicy, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *SchedulingPolicyCreate) createSpec() (*SchedulingPolicy, *sqlgraph.CreateSpec) { + var ( + _node = &SchedulingPolicy{config: _c.config} + _spec = sqlgraph.NewCreateSpec(schedulingpolicy.Table, sqlgraph.NewFieldSpec(schedulingpolicy.FieldID, field.TypeInt64)) + ) + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(schedulingpolicy.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(schedulingpolicy.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(schedulingpolicy.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Enabled(); ok { + _spec.SetField(schedulingpolicy.FieldEnabled, field.TypeBool, value) + _node.Enabled = value + } + if value, ok := _c.mutation.MonitorID(); ok { + _spec.SetField(schedulingpolicy.FieldMonitorID, field.TypeInt64, value) + _node.MonitorID = value + } + if value, ok := _c.mutation.AccountIds(); ok { + _spec.SetField(schedulingpolicy.FieldAccountIds, field.TypeJSON, value) + _node.AccountIds = value + } + if value, ok := _c.mutation.TriggerConsecutiveFailures(); ok { + _spec.SetField(schedulingpolicy.FieldTriggerConsecutiveFailures, field.TypeInt, value) + _node.TriggerConsecutiveFailures = value + } + if value, ok := _c.mutation.TriggerLatencyMs(); ok { + _spec.SetField(schedulingpolicy.FieldTriggerLatencyMs, field.TypeInt, value) + _node.TriggerLatencyMs = value + } + if value, ok := _c.mutation.ActionType(); ok { + _spec.SetField(schedulingpolicy.FieldActionType, field.TypeString, value) + _node.ActionType = value + } + if value, ok := _c.mutation.PauseMinutes(); ok { + _spec.SetField(schedulingpolicy.FieldPauseMinutes, field.TypeInt, value) + _node.PauseMinutes = value + } + if value, ok := _c.mutation.PriorityDelta(); ok { + _spec.SetField(schedulingpolicy.FieldPriorityDelta, field.TypeInt, value) + _node.PriorityDelta = value + } + if value, ok := _c.mutation.RecoverConsecutiveSuccesses(); ok { + _spec.SetField(schedulingpolicy.FieldRecoverConsecutiveSuccesses, field.TypeInt, value) + _node.RecoverConsecutiveSuccesses = value + } + if value, ok := _c.mutation.CooldownMinutes(); ok { + _spec.SetField(schedulingpolicy.FieldCooldownMinutes, field.TypeInt, value) + _node.CooldownMinutes = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.SchedulingPolicy.Create(). +// SetCreatedAt(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.SchedulingPolicyUpsert) { +// SetCreatedAt(v+v). +// }). +// Exec(ctx) +func (_c *SchedulingPolicyCreate) OnConflict(opts ...sql.ConflictOption) *SchedulingPolicyUpsertOne { + _c.conflict = opts + return &SchedulingPolicyUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.SchedulingPolicy.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *SchedulingPolicyCreate) OnConflictColumns(columns ...string) *SchedulingPolicyUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &SchedulingPolicyUpsertOne{ + create: _c, + } +} + +type ( + // SchedulingPolicyUpsertOne is the builder for "upsert"-ing + // one SchedulingPolicy node. + SchedulingPolicyUpsertOne struct { + create *SchedulingPolicyCreate + } + + // SchedulingPolicyUpsert is the "OnConflict" setter. + SchedulingPolicyUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *SchedulingPolicyUpsert) SetUpdatedAt(v time.Time) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdateUpdatedAt() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldUpdatedAt) + return u +} + +// SetName sets the "name" field. +func (u *SchedulingPolicyUpsert) SetName(v string) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdateName() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldName) + return u +} + +// SetEnabled sets the "enabled" field. +func (u *SchedulingPolicyUpsert) SetEnabled(v bool) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldEnabled, v) + return u +} + +// UpdateEnabled sets the "enabled" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdateEnabled() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldEnabled) + return u +} + +// SetMonitorID sets the "monitor_id" field. +func (u *SchedulingPolicyUpsert) SetMonitorID(v int64) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldMonitorID, v) + return u +} + +// UpdateMonitorID sets the "monitor_id" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdateMonitorID() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldMonitorID) + return u +} + +// AddMonitorID adds v to the "monitor_id" field. +func (u *SchedulingPolicyUpsert) AddMonitorID(v int64) *SchedulingPolicyUpsert { + u.Add(schedulingpolicy.FieldMonitorID, v) + return u +} + +// SetAccountIds sets the "account_ids" field. +func (u *SchedulingPolicyUpsert) SetAccountIds(v []int64) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldAccountIds, v) + return u +} + +// UpdateAccountIds sets the "account_ids" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdateAccountIds() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldAccountIds) + return u +} + +// SetTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field. +func (u *SchedulingPolicyUpsert) SetTriggerConsecutiveFailures(v int) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldTriggerConsecutiveFailures, v) + return u +} + +// UpdateTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdateTriggerConsecutiveFailures() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldTriggerConsecutiveFailures) + return u +} + +// AddTriggerConsecutiveFailures adds v to the "trigger_consecutive_failures" field. +func (u *SchedulingPolicyUpsert) AddTriggerConsecutiveFailures(v int) *SchedulingPolicyUpsert { + u.Add(schedulingpolicy.FieldTriggerConsecutiveFailures, v) + return u +} + +// SetTriggerLatencyMs sets the "trigger_latency_ms" field. +func (u *SchedulingPolicyUpsert) SetTriggerLatencyMs(v int) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldTriggerLatencyMs, v) + return u +} + +// UpdateTriggerLatencyMs sets the "trigger_latency_ms" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdateTriggerLatencyMs() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldTriggerLatencyMs) + return u +} + +// AddTriggerLatencyMs adds v to the "trigger_latency_ms" field. +func (u *SchedulingPolicyUpsert) AddTriggerLatencyMs(v int) *SchedulingPolicyUpsert { + u.Add(schedulingpolicy.FieldTriggerLatencyMs, v) + return u +} + +// SetActionType sets the "action_type" field. +func (u *SchedulingPolicyUpsert) SetActionType(v string) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldActionType, v) + return u +} + +// UpdateActionType sets the "action_type" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdateActionType() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldActionType) + return u +} + +// SetPauseMinutes sets the "pause_minutes" field. +func (u *SchedulingPolicyUpsert) SetPauseMinutes(v int) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldPauseMinutes, v) + return u +} + +// UpdatePauseMinutes sets the "pause_minutes" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdatePauseMinutes() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldPauseMinutes) + return u +} + +// AddPauseMinutes adds v to the "pause_minutes" field. +func (u *SchedulingPolicyUpsert) AddPauseMinutes(v int) *SchedulingPolicyUpsert { + u.Add(schedulingpolicy.FieldPauseMinutes, v) + return u +} + +// SetPriorityDelta sets the "priority_delta" field. +func (u *SchedulingPolicyUpsert) SetPriorityDelta(v int) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldPriorityDelta, v) + return u +} + +// UpdatePriorityDelta sets the "priority_delta" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdatePriorityDelta() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldPriorityDelta) + return u +} + +// AddPriorityDelta adds v to the "priority_delta" field. +func (u *SchedulingPolicyUpsert) AddPriorityDelta(v int) *SchedulingPolicyUpsert { + u.Add(schedulingpolicy.FieldPriorityDelta, v) + return u +} + +// SetRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field. +func (u *SchedulingPolicyUpsert) SetRecoverConsecutiveSuccesses(v int) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldRecoverConsecutiveSuccesses, v) + return u +} + +// UpdateRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdateRecoverConsecutiveSuccesses() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldRecoverConsecutiveSuccesses) + return u +} + +// AddRecoverConsecutiveSuccesses adds v to the "recover_consecutive_successes" field. +func (u *SchedulingPolicyUpsert) AddRecoverConsecutiveSuccesses(v int) *SchedulingPolicyUpsert { + u.Add(schedulingpolicy.FieldRecoverConsecutiveSuccesses, v) + return u +} + +// SetCooldownMinutes sets the "cooldown_minutes" field. +func (u *SchedulingPolicyUpsert) SetCooldownMinutes(v int) *SchedulingPolicyUpsert { + u.Set(schedulingpolicy.FieldCooldownMinutes, v) + return u +} + +// UpdateCooldownMinutes sets the "cooldown_minutes" field to the value that was provided on create. +func (u *SchedulingPolicyUpsert) UpdateCooldownMinutes() *SchedulingPolicyUpsert { + u.SetExcluded(schedulingpolicy.FieldCooldownMinutes) + return u +} + +// AddCooldownMinutes adds v to the "cooldown_minutes" field. +func (u *SchedulingPolicyUpsert) AddCooldownMinutes(v int) *SchedulingPolicyUpsert { + u.Add(schedulingpolicy.FieldCooldownMinutes, v) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.SchedulingPolicy.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *SchedulingPolicyUpsertOne) UpdateNewValues() *SchedulingPolicyUpsertOne { + 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.CreatedAt(); exists { + s.SetIgnore(schedulingpolicy.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.SchedulingPolicy.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SchedulingPolicyUpsertOne) Ignore() *SchedulingPolicyUpsertOne { + 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 *SchedulingPolicyUpsertOne) DoNothing() *SchedulingPolicyUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SchedulingPolicyCreate.OnConflict +// documentation for more info. +func (u *SchedulingPolicyUpsertOne) Update(set func(*SchedulingPolicyUpsert)) *SchedulingPolicyUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SchedulingPolicyUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *SchedulingPolicyUpsertOne) SetUpdatedAt(v time.Time) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdateUpdatedAt() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetName sets the "name" field. +func (u *SchedulingPolicyUpsertOne) SetName(v string) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdateName() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateName() + }) +} + +// SetEnabled sets the "enabled" field. +func (u *SchedulingPolicyUpsertOne) SetEnabled(v bool) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetEnabled(v) + }) +} + +// UpdateEnabled sets the "enabled" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdateEnabled() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateEnabled() + }) +} + +// SetMonitorID sets the "monitor_id" field. +func (u *SchedulingPolicyUpsertOne) SetMonitorID(v int64) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetMonitorID(v) + }) +} + +// AddMonitorID adds v to the "monitor_id" field. +func (u *SchedulingPolicyUpsertOne) AddMonitorID(v int64) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddMonitorID(v) + }) +} + +// UpdateMonitorID sets the "monitor_id" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdateMonitorID() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateMonitorID() + }) +} + +// SetAccountIds sets the "account_ids" field. +func (u *SchedulingPolicyUpsertOne) SetAccountIds(v []int64) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetAccountIds(v) + }) +} + +// UpdateAccountIds sets the "account_ids" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdateAccountIds() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateAccountIds() + }) +} + +// SetTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field. +func (u *SchedulingPolicyUpsertOne) SetTriggerConsecutiveFailures(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetTriggerConsecutiveFailures(v) + }) +} + +// AddTriggerConsecutiveFailures adds v to the "trigger_consecutive_failures" field. +func (u *SchedulingPolicyUpsertOne) AddTriggerConsecutiveFailures(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddTriggerConsecutiveFailures(v) + }) +} + +// UpdateTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdateTriggerConsecutiveFailures() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateTriggerConsecutiveFailures() + }) +} + +// SetTriggerLatencyMs sets the "trigger_latency_ms" field. +func (u *SchedulingPolicyUpsertOne) SetTriggerLatencyMs(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetTriggerLatencyMs(v) + }) +} + +// AddTriggerLatencyMs adds v to the "trigger_latency_ms" field. +func (u *SchedulingPolicyUpsertOne) AddTriggerLatencyMs(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddTriggerLatencyMs(v) + }) +} + +// UpdateTriggerLatencyMs sets the "trigger_latency_ms" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdateTriggerLatencyMs() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateTriggerLatencyMs() + }) +} + +// SetActionType sets the "action_type" field. +func (u *SchedulingPolicyUpsertOne) SetActionType(v string) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetActionType(v) + }) +} + +// UpdateActionType sets the "action_type" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdateActionType() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateActionType() + }) +} + +// SetPauseMinutes sets the "pause_minutes" field. +func (u *SchedulingPolicyUpsertOne) SetPauseMinutes(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetPauseMinutes(v) + }) +} + +// AddPauseMinutes adds v to the "pause_minutes" field. +func (u *SchedulingPolicyUpsertOne) AddPauseMinutes(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddPauseMinutes(v) + }) +} + +// UpdatePauseMinutes sets the "pause_minutes" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdatePauseMinutes() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdatePauseMinutes() + }) +} + +// SetPriorityDelta sets the "priority_delta" field. +func (u *SchedulingPolicyUpsertOne) SetPriorityDelta(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetPriorityDelta(v) + }) +} + +// AddPriorityDelta adds v to the "priority_delta" field. +func (u *SchedulingPolicyUpsertOne) AddPriorityDelta(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddPriorityDelta(v) + }) +} + +// UpdatePriorityDelta sets the "priority_delta" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdatePriorityDelta() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdatePriorityDelta() + }) +} + +// SetRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field. +func (u *SchedulingPolicyUpsertOne) SetRecoverConsecutiveSuccesses(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetRecoverConsecutiveSuccesses(v) + }) +} + +// AddRecoverConsecutiveSuccesses adds v to the "recover_consecutive_successes" field. +func (u *SchedulingPolicyUpsertOne) AddRecoverConsecutiveSuccesses(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddRecoverConsecutiveSuccesses(v) + }) +} + +// UpdateRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdateRecoverConsecutiveSuccesses() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateRecoverConsecutiveSuccesses() + }) +} + +// SetCooldownMinutes sets the "cooldown_minutes" field. +func (u *SchedulingPolicyUpsertOne) SetCooldownMinutes(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetCooldownMinutes(v) + }) +} + +// AddCooldownMinutes adds v to the "cooldown_minutes" field. +func (u *SchedulingPolicyUpsertOne) AddCooldownMinutes(v int) *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddCooldownMinutes(v) + }) +} + +// UpdateCooldownMinutes sets the "cooldown_minutes" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertOne) UpdateCooldownMinutes() *SchedulingPolicyUpsertOne { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateCooldownMinutes() + }) +} + +// Exec executes the query. +func (u *SchedulingPolicyUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for SchedulingPolicyCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SchedulingPolicyUpsertOne) 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 *SchedulingPolicyUpsertOne) ID(ctx context.Context) (id int64, err error) { + 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 *SchedulingPolicyUpsertOne) IDX(ctx context.Context) int64 { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// SchedulingPolicyCreateBulk is the builder for creating many SchedulingPolicy entities in bulk. +type SchedulingPolicyCreateBulk struct { + config + err error + builders []*SchedulingPolicyCreate + conflict []sql.ConflictOption +} + +// Save creates the SchedulingPolicy entities in the database. +func (_c *SchedulingPolicyCreateBulk) Save(ctx context.Context) ([]*SchedulingPolicy, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*SchedulingPolicy, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*SchedulingPolicyMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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 + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *SchedulingPolicyCreateBulk) SaveX(ctx context.Context) []*SchedulingPolicy { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SchedulingPolicyCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SchedulingPolicyCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.SchedulingPolicy.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.SchedulingPolicyUpsert) { +// SetCreatedAt(v+v). +// }). +// Exec(ctx) +func (_c *SchedulingPolicyCreateBulk) OnConflict(opts ...sql.ConflictOption) *SchedulingPolicyUpsertBulk { + _c.conflict = opts + return &SchedulingPolicyUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.SchedulingPolicy.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *SchedulingPolicyCreateBulk) OnConflictColumns(columns ...string) *SchedulingPolicyUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &SchedulingPolicyUpsertBulk{ + create: _c, + } +} + +// SchedulingPolicyUpsertBulk is the builder for "upsert"-ing +// a bulk of SchedulingPolicy nodes. +type SchedulingPolicyUpsertBulk struct { + create *SchedulingPolicyCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.SchedulingPolicy.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *SchedulingPolicyUpsertBulk) UpdateNewValues() *SchedulingPolicyUpsertBulk { + 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.CreatedAt(); exists { + s.SetIgnore(schedulingpolicy.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.SchedulingPolicy.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SchedulingPolicyUpsertBulk) Ignore() *SchedulingPolicyUpsertBulk { + 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 *SchedulingPolicyUpsertBulk) DoNothing() *SchedulingPolicyUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SchedulingPolicyCreateBulk.OnConflict +// documentation for more info. +func (u *SchedulingPolicyUpsertBulk) Update(set func(*SchedulingPolicyUpsert)) *SchedulingPolicyUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SchedulingPolicyUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *SchedulingPolicyUpsertBulk) SetUpdatedAt(v time.Time) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdateUpdatedAt() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetName sets the "name" field. +func (u *SchedulingPolicyUpsertBulk) SetName(v string) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdateName() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateName() + }) +} + +// SetEnabled sets the "enabled" field. +func (u *SchedulingPolicyUpsertBulk) SetEnabled(v bool) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetEnabled(v) + }) +} + +// UpdateEnabled sets the "enabled" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdateEnabled() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateEnabled() + }) +} + +// SetMonitorID sets the "monitor_id" field. +func (u *SchedulingPolicyUpsertBulk) SetMonitorID(v int64) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetMonitorID(v) + }) +} + +// AddMonitorID adds v to the "monitor_id" field. +func (u *SchedulingPolicyUpsertBulk) AddMonitorID(v int64) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddMonitorID(v) + }) +} + +// UpdateMonitorID sets the "monitor_id" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdateMonitorID() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateMonitorID() + }) +} + +// SetAccountIds sets the "account_ids" field. +func (u *SchedulingPolicyUpsertBulk) SetAccountIds(v []int64) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetAccountIds(v) + }) +} + +// UpdateAccountIds sets the "account_ids" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdateAccountIds() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateAccountIds() + }) +} + +// SetTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field. +func (u *SchedulingPolicyUpsertBulk) SetTriggerConsecutiveFailures(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetTriggerConsecutiveFailures(v) + }) +} + +// AddTriggerConsecutiveFailures adds v to the "trigger_consecutive_failures" field. +func (u *SchedulingPolicyUpsertBulk) AddTriggerConsecutiveFailures(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddTriggerConsecutiveFailures(v) + }) +} + +// UpdateTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdateTriggerConsecutiveFailures() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateTriggerConsecutiveFailures() + }) +} + +// SetTriggerLatencyMs sets the "trigger_latency_ms" field. +func (u *SchedulingPolicyUpsertBulk) SetTriggerLatencyMs(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetTriggerLatencyMs(v) + }) +} + +// AddTriggerLatencyMs adds v to the "trigger_latency_ms" field. +func (u *SchedulingPolicyUpsertBulk) AddTriggerLatencyMs(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddTriggerLatencyMs(v) + }) +} + +// UpdateTriggerLatencyMs sets the "trigger_latency_ms" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdateTriggerLatencyMs() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateTriggerLatencyMs() + }) +} + +// SetActionType sets the "action_type" field. +func (u *SchedulingPolicyUpsertBulk) SetActionType(v string) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetActionType(v) + }) +} + +// UpdateActionType sets the "action_type" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdateActionType() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateActionType() + }) +} + +// SetPauseMinutes sets the "pause_minutes" field. +func (u *SchedulingPolicyUpsertBulk) SetPauseMinutes(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetPauseMinutes(v) + }) +} + +// AddPauseMinutes adds v to the "pause_minutes" field. +func (u *SchedulingPolicyUpsertBulk) AddPauseMinutes(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddPauseMinutes(v) + }) +} + +// UpdatePauseMinutes sets the "pause_minutes" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdatePauseMinutes() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdatePauseMinutes() + }) +} + +// SetPriorityDelta sets the "priority_delta" field. +func (u *SchedulingPolicyUpsertBulk) SetPriorityDelta(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetPriorityDelta(v) + }) +} + +// AddPriorityDelta adds v to the "priority_delta" field. +func (u *SchedulingPolicyUpsertBulk) AddPriorityDelta(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddPriorityDelta(v) + }) +} + +// UpdatePriorityDelta sets the "priority_delta" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdatePriorityDelta() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdatePriorityDelta() + }) +} + +// SetRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field. +func (u *SchedulingPolicyUpsertBulk) SetRecoverConsecutiveSuccesses(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetRecoverConsecutiveSuccesses(v) + }) +} + +// AddRecoverConsecutiveSuccesses adds v to the "recover_consecutive_successes" field. +func (u *SchedulingPolicyUpsertBulk) AddRecoverConsecutiveSuccesses(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddRecoverConsecutiveSuccesses(v) + }) +} + +// UpdateRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdateRecoverConsecutiveSuccesses() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateRecoverConsecutiveSuccesses() + }) +} + +// SetCooldownMinutes sets the "cooldown_minutes" field. +func (u *SchedulingPolicyUpsertBulk) SetCooldownMinutes(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.SetCooldownMinutes(v) + }) +} + +// AddCooldownMinutes adds v to the "cooldown_minutes" field. +func (u *SchedulingPolicyUpsertBulk) AddCooldownMinutes(v int) *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.AddCooldownMinutes(v) + }) +} + +// UpdateCooldownMinutes sets the "cooldown_minutes" field to the value that was provided on create. +func (u *SchedulingPolicyUpsertBulk) UpdateCooldownMinutes() *SchedulingPolicyUpsertBulk { + return u.Update(func(s *SchedulingPolicyUpsert) { + s.UpdateCooldownMinutes() + }) +} + +// Exec executes the query. +func (u *SchedulingPolicyUpsertBulk) 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("ent: OnConflict was set for builder %d. Set it on the SchedulingPolicyCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for SchedulingPolicyCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SchedulingPolicyUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/ent/schedulingpolicy_delete.go b/backend/ent/schedulingpolicy_delete.go new file mode 100644 index 000000000000..58cbe76e96f4 --- /dev/null +++ b/backend/ent/schedulingpolicy_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/Wei-Shaw/sub2api/ent/predicate" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" +) + +// SchedulingPolicyDelete is the builder for deleting a SchedulingPolicy entity. +type SchedulingPolicyDelete struct { + config + hooks []Hook + mutation *SchedulingPolicyMutation +} + +// Where appends a list predicates to the SchedulingPolicyDelete builder. +func (_d *SchedulingPolicyDelete) Where(ps ...predicate.SchedulingPolicy) *SchedulingPolicyDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *SchedulingPolicyDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SchedulingPolicyDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *SchedulingPolicyDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(schedulingpolicy.Table, sqlgraph.NewFieldSpec(schedulingpolicy.FieldID, field.TypeInt64)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// SchedulingPolicyDeleteOne is the builder for deleting a single SchedulingPolicy entity. +type SchedulingPolicyDeleteOne struct { + _d *SchedulingPolicyDelete +} + +// Where appends a list predicates to the SchedulingPolicyDelete builder. +func (_d *SchedulingPolicyDeleteOne) Where(ps ...predicate.SchedulingPolicy) *SchedulingPolicyDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *SchedulingPolicyDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{schedulingpolicy.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SchedulingPolicyDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/ent/schedulingpolicy_query.go b/backend/ent/schedulingpolicy_query.go new file mode 100644 index 000000000000..b082805d8f7b --- /dev/null +++ b/backend/ent/schedulingpolicy_query.go @@ -0,0 +1,564 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/Wei-Shaw/sub2api/ent/predicate" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" +) + +// SchedulingPolicyQuery is the builder for querying SchedulingPolicy entities. +type SchedulingPolicyQuery struct { + config + ctx *QueryContext + order []schedulingpolicy.OrderOption + inters []Interceptor + predicates []predicate.SchedulingPolicy + 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 SchedulingPolicyQuery builder. +func (_q *SchedulingPolicyQuery) Where(ps ...predicate.SchedulingPolicy) *SchedulingPolicyQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *SchedulingPolicyQuery) Limit(limit int) *SchedulingPolicyQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *SchedulingPolicyQuery) Offset(offset int) *SchedulingPolicyQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *SchedulingPolicyQuery) Unique(unique bool) *SchedulingPolicyQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *SchedulingPolicyQuery) Order(o ...schedulingpolicy.OrderOption) *SchedulingPolicyQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first SchedulingPolicy entity from the query. +// Returns a *NotFoundError when no SchedulingPolicy was found. +func (_q *SchedulingPolicyQuery) First(ctx context.Context) (*SchedulingPolicy, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{schedulingpolicy.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *SchedulingPolicyQuery) FirstX(ctx context.Context) *SchedulingPolicy { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first SchedulingPolicy ID from the query. +// Returns a *NotFoundError when no SchedulingPolicy ID was found. +func (_q *SchedulingPolicyQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{schedulingpolicy.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *SchedulingPolicyQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single SchedulingPolicy entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one SchedulingPolicy entity is found. +// Returns a *NotFoundError when no SchedulingPolicy entities are found. +func (_q *SchedulingPolicyQuery) Only(ctx context.Context) (*SchedulingPolicy, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{schedulingpolicy.Label} + default: + return nil, &NotSingularError{schedulingpolicy.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *SchedulingPolicyQuery) OnlyX(ctx context.Context) *SchedulingPolicy { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only SchedulingPolicy ID in the query. +// Returns a *NotSingularError when more than one SchedulingPolicy ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *SchedulingPolicyQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{schedulingpolicy.Label} + default: + err = &NotSingularError{schedulingpolicy.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *SchedulingPolicyQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of SchedulingPolicies. +func (_q *SchedulingPolicyQuery) All(ctx context.Context) ([]*SchedulingPolicy, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*SchedulingPolicy, *SchedulingPolicyQuery]() + return withInterceptors[[]*SchedulingPolicy](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *SchedulingPolicyQuery) AllX(ctx context.Context) []*SchedulingPolicy { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of SchedulingPolicy IDs. +func (_q *SchedulingPolicyQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(schedulingpolicy.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *SchedulingPolicyQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *SchedulingPolicyQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*SchedulingPolicyQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *SchedulingPolicyQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *SchedulingPolicyQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *SchedulingPolicyQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the SchedulingPolicyQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *SchedulingPolicyQuery) Clone() *SchedulingPolicyQuery { + if _q == nil { + return nil + } + return &SchedulingPolicyQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]schedulingpolicy.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.SchedulingPolicy{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// 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 { +// CreatedAt time.Time `json:"created_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.SchedulingPolicy.Query(). +// GroupBy(schedulingpolicy.FieldCreatedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *SchedulingPolicyQuery) GroupBy(field string, fields ...string) *SchedulingPolicyGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &SchedulingPolicyGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = schedulingpolicy.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 { +// CreatedAt time.Time `json:"created_at,omitempty"` +// } +// +// client.SchedulingPolicy.Query(). +// Select(schedulingpolicy.FieldCreatedAt). +// Scan(ctx, &v) +func (_q *SchedulingPolicyQuery) Select(fields ...string) *SchedulingPolicySelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &SchedulingPolicySelect{SchedulingPolicyQuery: _q} + sbuild.label = schedulingpolicy.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a SchedulingPolicySelect configured with the given aggregations. +func (_q *SchedulingPolicyQuery) Aggregate(fns ...AggregateFunc) *SchedulingPolicySelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *SchedulingPolicyQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !schedulingpolicy.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *SchedulingPolicyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SchedulingPolicy, error) { + var ( + nodes = []*SchedulingPolicy{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*SchedulingPolicy).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &SchedulingPolicy{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *SchedulingPolicyQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *SchedulingPolicyQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(schedulingpolicy.Table, schedulingpolicy.Columns, sqlgraph.NewFieldSpec(schedulingpolicy.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, schedulingpolicy.FieldID) + for i := range fields { + if fields[i] != schedulingpolicy.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *SchedulingPolicyQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(schedulingpolicy.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = schedulingpolicy.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *SchedulingPolicyQuery) ForUpdate(opts ...sql.LockOption) *SchedulingPolicyQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *SchedulingPolicyQuery) ForShare(opts ...sql.LockOption) *SchedulingPolicyQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// SchedulingPolicyGroupBy is the group-by builder for SchedulingPolicy entities. +type SchedulingPolicyGroupBy struct { + selector + build *SchedulingPolicyQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *SchedulingPolicyGroupBy) Aggregate(fns ...AggregateFunc) *SchedulingPolicyGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *SchedulingPolicyGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SchedulingPolicyQuery, *SchedulingPolicyGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *SchedulingPolicyGroupBy) sqlScan(ctx context.Context, root *SchedulingPolicyQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// SchedulingPolicySelect is the builder for selecting fields of SchedulingPolicy entities. +type SchedulingPolicySelect struct { + *SchedulingPolicyQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *SchedulingPolicySelect) Aggregate(fns ...AggregateFunc) *SchedulingPolicySelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *SchedulingPolicySelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SchedulingPolicyQuery, *SchedulingPolicySelect](ctx, _s.SchedulingPolicyQuery, _s, _s.inters, v) +} + +func (_s *SchedulingPolicySelect) sqlScan(ctx context.Context, root *SchedulingPolicyQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/backend/ent/schedulingpolicy_update.go b/backend/ent/schedulingpolicy_update.go new file mode 100644 index 000000000000..d390fec43931 --- /dev/null +++ b/backend/ent/schedulingpolicy_update.go @@ -0,0 +1,829 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql/sqljson" + "entgo.io/ent/schema/field" + "github.com/Wei-Shaw/sub2api/ent/predicate" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" +) + +// SchedulingPolicyUpdate is the builder for updating SchedulingPolicy entities. +type SchedulingPolicyUpdate struct { + config + hooks []Hook + mutation *SchedulingPolicyMutation +} + +// Where appends a list predicates to the SchedulingPolicyUpdate builder. +func (_u *SchedulingPolicyUpdate) Where(ps ...predicate.SchedulingPolicy) *SchedulingPolicyUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *SchedulingPolicyUpdate) SetUpdatedAt(v time.Time) *SchedulingPolicyUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetName sets the "name" field. +func (_u *SchedulingPolicyUpdate) SetName(v string) *SchedulingPolicyUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *SchedulingPolicyUpdate) SetNillableName(v *string) *SchedulingPolicyUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetEnabled sets the "enabled" field. +func (_u *SchedulingPolicyUpdate) SetEnabled(v bool) *SchedulingPolicyUpdate { + _u.mutation.SetEnabled(v) + return _u +} + +// SetNillableEnabled sets the "enabled" field if the given value is not nil. +func (_u *SchedulingPolicyUpdate) SetNillableEnabled(v *bool) *SchedulingPolicyUpdate { + if v != nil { + _u.SetEnabled(*v) + } + return _u +} + +// SetMonitorID sets the "monitor_id" field. +func (_u *SchedulingPolicyUpdate) SetMonitorID(v int64) *SchedulingPolicyUpdate { + _u.mutation.ResetMonitorID() + _u.mutation.SetMonitorID(v) + return _u +} + +// SetNillableMonitorID sets the "monitor_id" field if the given value is not nil. +func (_u *SchedulingPolicyUpdate) SetNillableMonitorID(v *int64) *SchedulingPolicyUpdate { + if v != nil { + _u.SetMonitorID(*v) + } + return _u +} + +// AddMonitorID adds value to the "monitor_id" field. +func (_u *SchedulingPolicyUpdate) AddMonitorID(v int64) *SchedulingPolicyUpdate { + _u.mutation.AddMonitorID(v) + return _u +} + +// SetAccountIds sets the "account_ids" field. +func (_u *SchedulingPolicyUpdate) SetAccountIds(v []int64) *SchedulingPolicyUpdate { + _u.mutation.SetAccountIds(v) + return _u +} + +// AppendAccountIds appends value to the "account_ids" field. +func (_u *SchedulingPolicyUpdate) AppendAccountIds(v []int64) *SchedulingPolicyUpdate { + _u.mutation.AppendAccountIds(v) + return _u +} + +// SetTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field. +func (_u *SchedulingPolicyUpdate) SetTriggerConsecutiveFailures(v int) *SchedulingPolicyUpdate { + _u.mutation.ResetTriggerConsecutiveFailures() + _u.mutation.SetTriggerConsecutiveFailures(v) + return _u +} + +// SetNillableTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field if the given value is not nil. +func (_u *SchedulingPolicyUpdate) SetNillableTriggerConsecutiveFailures(v *int) *SchedulingPolicyUpdate { + if v != nil { + _u.SetTriggerConsecutiveFailures(*v) + } + return _u +} + +// AddTriggerConsecutiveFailures adds value to the "trigger_consecutive_failures" field. +func (_u *SchedulingPolicyUpdate) AddTriggerConsecutiveFailures(v int) *SchedulingPolicyUpdate { + _u.mutation.AddTriggerConsecutiveFailures(v) + return _u +} + +// SetTriggerLatencyMs sets the "trigger_latency_ms" field. +func (_u *SchedulingPolicyUpdate) SetTriggerLatencyMs(v int) *SchedulingPolicyUpdate { + _u.mutation.ResetTriggerLatencyMs() + _u.mutation.SetTriggerLatencyMs(v) + return _u +} + +// SetNillableTriggerLatencyMs sets the "trigger_latency_ms" field if the given value is not nil. +func (_u *SchedulingPolicyUpdate) SetNillableTriggerLatencyMs(v *int) *SchedulingPolicyUpdate { + if v != nil { + _u.SetTriggerLatencyMs(*v) + } + return _u +} + +// AddTriggerLatencyMs adds value to the "trigger_latency_ms" field. +func (_u *SchedulingPolicyUpdate) AddTriggerLatencyMs(v int) *SchedulingPolicyUpdate { + _u.mutation.AddTriggerLatencyMs(v) + return _u +} + +// SetActionType sets the "action_type" field. +func (_u *SchedulingPolicyUpdate) SetActionType(v string) *SchedulingPolicyUpdate { + _u.mutation.SetActionType(v) + return _u +} + +// SetNillableActionType sets the "action_type" field if the given value is not nil. +func (_u *SchedulingPolicyUpdate) SetNillableActionType(v *string) *SchedulingPolicyUpdate { + if v != nil { + _u.SetActionType(*v) + } + return _u +} + +// SetPauseMinutes sets the "pause_minutes" field. +func (_u *SchedulingPolicyUpdate) SetPauseMinutes(v int) *SchedulingPolicyUpdate { + _u.mutation.ResetPauseMinutes() + _u.mutation.SetPauseMinutes(v) + return _u +} + +// SetNillablePauseMinutes sets the "pause_minutes" field if the given value is not nil. +func (_u *SchedulingPolicyUpdate) SetNillablePauseMinutes(v *int) *SchedulingPolicyUpdate { + if v != nil { + _u.SetPauseMinutes(*v) + } + return _u +} + +// AddPauseMinutes adds value to the "pause_minutes" field. +func (_u *SchedulingPolicyUpdate) AddPauseMinutes(v int) *SchedulingPolicyUpdate { + _u.mutation.AddPauseMinutes(v) + return _u +} + +// SetPriorityDelta sets the "priority_delta" field. +func (_u *SchedulingPolicyUpdate) SetPriorityDelta(v int) *SchedulingPolicyUpdate { + _u.mutation.ResetPriorityDelta() + _u.mutation.SetPriorityDelta(v) + return _u +} + +// SetNillablePriorityDelta sets the "priority_delta" field if the given value is not nil. +func (_u *SchedulingPolicyUpdate) SetNillablePriorityDelta(v *int) *SchedulingPolicyUpdate { + if v != nil { + _u.SetPriorityDelta(*v) + } + return _u +} + +// AddPriorityDelta adds value to the "priority_delta" field. +func (_u *SchedulingPolicyUpdate) AddPriorityDelta(v int) *SchedulingPolicyUpdate { + _u.mutation.AddPriorityDelta(v) + return _u +} + +// SetRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field. +func (_u *SchedulingPolicyUpdate) SetRecoverConsecutiveSuccesses(v int) *SchedulingPolicyUpdate { + _u.mutation.ResetRecoverConsecutiveSuccesses() + _u.mutation.SetRecoverConsecutiveSuccesses(v) + return _u +} + +// SetNillableRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field if the given value is not nil. +func (_u *SchedulingPolicyUpdate) SetNillableRecoverConsecutiveSuccesses(v *int) *SchedulingPolicyUpdate { + if v != nil { + _u.SetRecoverConsecutiveSuccesses(*v) + } + return _u +} + +// AddRecoverConsecutiveSuccesses adds value to the "recover_consecutive_successes" field. +func (_u *SchedulingPolicyUpdate) AddRecoverConsecutiveSuccesses(v int) *SchedulingPolicyUpdate { + _u.mutation.AddRecoverConsecutiveSuccesses(v) + return _u +} + +// SetCooldownMinutes sets the "cooldown_minutes" field. +func (_u *SchedulingPolicyUpdate) SetCooldownMinutes(v int) *SchedulingPolicyUpdate { + _u.mutation.ResetCooldownMinutes() + _u.mutation.SetCooldownMinutes(v) + return _u +} + +// SetNillableCooldownMinutes sets the "cooldown_minutes" field if the given value is not nil. +func (_u *SchedulingPolicyUpdate) SetNillableCooldownMinutes(v *int) *SchedulingPolicyUpdate { + if v != nil { + _u.SetCooldownMinutes(*v) + } + return _u +} + +// AddCooldownMinutes adds value to the "cooldown_minutes" field. +func (_u *SchedulingPolicyUpdate) AddCooldownMinutes(v int) *SchedulingPolicyUpdate { + _u.mutation.AddCooldownMinutes(v) + return _u +} + +// Mutation returns the SchedulingPolicyMutation object of the builder. +func (_u *SchedulingPolicyUpdate) Mutation() *SchedulingPolicyMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *SchedulingPolicyUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SchedulingPolicyUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *SchedulingPolicyUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SchedulingPolicyUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *SchedulingPolicyUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := schedulingpolicy.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SchedulingPolicyUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := schedulingpolicy.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.name": %w`, err)} + } + } + if v, ok := _u.mutation.TriggerConsecutiveFailures(); ok { + if err := schedulingpolicy.TriggerConsecutiveFailuresValidator(v); err != nil { + return &ValidationError{Name: "trigger_consecutive_failures", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.trigger_consecutive_failures": %w`, err)} + } + } + if v, ok := _u.mutation.TriggerLatencyMs(); ok { + if err := schedulingpolicy.TriggerLatencyMsValidator(v); err != nil { + return &ValidationError{Name: "trigger_latency_ms", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.trigger_latency_ms": %w`, err)} + } + } + if v, ok := _u.mutation.ActionType(); ok { + if err := schedulingpolicy.ActionTypeValidator(v); err != nil { + return &ValidationError{Name: "action_type", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.action_type": %w`, err)} + } + } + if v, ok := _u.mutation.PauseMinutes(); ok { + if err := schedulingpolicy.PauseMinutesValidator(v); err != nil { + return &ValidationError{Name: "pause_minutes", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.pause_minutes": %w`, err)} + } + } + if v, ok := _u.mutation.PriorityDelta(); ok { + if err := schedulingpolicy.PriorityDeltaValidator(v); err != nil { + return &ValidationError{Name: "priority_delta", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.priority_delta": %w`, err)} + } + } + if v, ok := _u.mutation.RecoverConsecutiveSuccesses(); ok { + if err := schedulingpolicy.RecoverConsecutiveSuccessesValidator(v); err != nil { + return &ValidationError{Name: "recover_consecutive_successes", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.recover_consecutive_successes": %w`, err)} + } + } + if v, ok := _u.mutation.CooldownMinutes(); ok { + if err := schedulingpolicy.CooldownMinutesValidator(v); err != nil { + return &ValidationError{Name: "cooldown_minutes", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.cooldown_minutes": %w`, err)} + } + } + return nil +} + +func (_u *SchedulingPolicyUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(schedulingpolicy.Table, schedulingpolicy.Columns, sqlgraph.NewFieldSpec(schedulingpolicy.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(schedulingpolicy.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(schedulingpolicy.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Enabled(); ok { + _spec.SetField(schedulingpolicy.FieldEnabled, field.TypeBool, value) + } + if value, ok := _u.mutation.MonitorID(); ok { + _spec.SetField(schedulingpolicy.FieldMonitorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedMonitorID(); ok { + _spec.AddField(schedulingpolicy.FieldMonitorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AccountIds(); ok { + _spec.SetField(schedulingpolicy.FieldAccountIds, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedAccountIds(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, schedulingpolicy.FieldAccountIds, value) + }) + } + if value, ok := _u.mutation.TriggerConsecutiveFailures(); ok { + _spec.SetField(schedulingpolicy.FieldTriggerConsecutiveFailures, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedTriggerConsecutiveFailures(); ok { + _spec.AddField(schedulingpolicy.FieldTriggerConsecutiveFailures, field.TypeInt, value) + } + if value, ok := _u.mutation.TriggerLatencyMs(); ok { + _spec.SetField(schedulingpolicy.FieldTriggerLatencyMs, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedTriggerLatencyMs(); ok { + _spec.AddField(schedulingpolicy.FieldTriggerLatencyMs, field.TypeInt, value) + } + if value, ok := _u.mutation.ActionType(); ok { + _spec.SetField(schedulingpolicy.FieldActionType, field.TypeString, value) + } + if value, ok := _u.mutation.PauseMinutes(); ok { + _spec.SetField(schedulingpolicy.FieldPauseMinutes, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedPauseMinutes(); ok { + _spec.AddField(schedulingpolicy.FieldPauseMinutes, field.TypeInt, value) + } + if value, ok := _u.mutation.PriorityDelta(); ok { + _spec.SetField(schedulingpolicy.FieldPriorityDelta, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedPriorityDelta(); ok { + _spec.AddField(schedulingpolicy.FieldPriorityDelta, field.TypeInt, value) + } + if value, ok := _u.mutation.RecoverConsecutiveSuccesses(); ok { + _spec.SetField(schedulingpolicy.FieldRecoverConsecutiveSuccesses, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedRecoverConsecutiveSuccesses(); ok { + _spec.AddField(schedulingpolicy.FieldRecoverConsecutiveSuccesses, field.TypeInt, value) + } + if value, ok := _u.mutation.CooldownMinutes(); ok { + _spec.SetField(schedulingpolicy.FieldCooldownMinutes, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedCooldownMinutes(); ok { + _spec.AddField(schedulingpolicy.FieldCooldownMinutes, field.TypeInt, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{schedulingpolicy.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// SchedulingPolicyUpdateOne is the builder for updating a single SchedulingPolicy entity. +type SchedulingPolicyUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SchedulingPolicyMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *SchedulingPolicyUpdateOne) SetUpdatedAt(v time.Time) *SchedulingPolicyUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetName sets the "name" field. +func (_u *SchedulingPolicyUpdateOne) SetName(v string) *SchedulingPolicyUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *SchedulingPolicyUpdateOne) SetNillableName(v *string) *SchedulingPolicyUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetEnabled sets the "enabled" field. +func (_u *SchedulingPolicyUpdateOne) SetEnabled(v bool) *SchedulingPolicyUpdateOne { + _u.mutation.SetEnabled(v) + return _u +} + +// SetNillableEnabled sets the "enabled" field if the given value is not nil. +func (_u *SchedulingPolicyUpdateOne) SetNillableEnabled(v *bool) *SchedulingPolicyUpdateOne { + if v != nil { + _u.SetEnabled(*v) + } + return _u +} + +// SetMonitorID sets the "monitor_id" field. +func (_u *SchedulingPolicyUpdateOne) SetMonitorID(v int64) *SchedulingPolicyUpdateOne { + _u.mutation.ResetMonitorID() + _u.mutation.SetMonitorID(v) + return _u +} + +// SetNillableMonitorID sets the "monitor_id" field if the given value is not nil. +func (_u *SchedulingPolicyUpdateOne) SetNillableMonitorID(v *int64) *SchedulingPolicyUpdateOne { + if v != nil { + _u.SetMonitorID(*v) + } + return _u +} + +// AddMonitorID adds value to the "monitor_id" field. +func (_u *SchedulingPolicyUpdateOne) AddMonitorID(v int64) *SchedulingPolicyUpdateOne { + _u.mutation.AddMonitorID(v) + return _u +} + +// SetAccountIds sets the "account_ids" field. +func (_u *SchedulingPolicyUpdateOne) SetAccountIds(v []int64) *SchedulingPolicyUpdateOne { + _u.mutation.SetAccountIds(v) + return _u +} + +// AppendAccountIds appends value to the "account_ids" field. +func (_u *SchedulingPolicyUpdateOne) AppendAccountIds(v []int64) *SchedulingPolicyUpdateOne { + _u.mutation.AppendAccountIds(v) + return _u +} + +// SetTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field. +func (_u *SchedulingPolicyUpdateOne) SetTriggerConsecutiveFailures(v int) *SchedulingPolicyUpdateOne { + _u.mutation.ResetTriggerConsecutiveFailures() + _u.mutation.SetTriggerConsecutiveFailures(v) + return _u +} + +// SetNillableTriggerConsecutiveFailures sets the "trigger_consecutive_failures" field if the given value is not nil. +func (_u *SchedulingPolicyUpdateOne) SetNillableTriggerConsecutiveFailures(v *int) *SchedulingPolicyUpdateOne { + if v != nil { + _u.SetTriggerConsecutiveFailures(*v) + } + return _u +} + +// AddTriggerConsecutiveFailures adds value to the "trigger_consecutive_failures" field. +func (_u *SchedulingPolicyUpdateOne) AddTriggerConsecutiveFailures(v int) *SchedulingPolicyUpdateOne { + _u.mutation.AddTriggerConsecutiveFailures(v) + return _u +} + +// SetTriggerLatencyMs sets the "trigger_latency_ms" field. +func (_u *SchedulingPolicyUpdateOne) SetTriggerLatencyMs(v int) *SchedulingPolicyUpdateOne { + _u.mutation.ResetTriggerLatencyMs() + _u.mutation.SetTriggerLatencyMs(v) + return _u +} + +// SetNillableTriggerLatencyMs sets the "trigger_latency_ms" field if the given value is not nil. +func (_u *SchedulingPolicyUpdateOne) SetNillableTriggerLatencyMs(v *int) *SchedulingPolicyUpdateOne { + if v != nil { + _u.SetTriggerLatencyMs(*v) + } + return _u +} + +// AddTriggerLatencyMs adds value to the "trigger_latency_ms" field. +func (_u *SchedulingPolicyUpdateOne) AddTriggerLatencyMs(v int) *SchedulingPolicyUpdateOne { + _u.mutation.AddTriggerLatencyMs(v) + return _u +} + +// SetActionType sets the "action_type" field. +func (_u *SchedulingPolicyUpdateOne) SetActionType(v string) *SchedulingPolicyUpdateOne { + _u.mutation.SetActionType(v) + return _u +} + +// SetNillableActionType sets the "action_type" field if the given value is not nil. +func (_u *SchedulingPolicyUpdateOne) SetNillableActionType(v *string) *SchedulingPolicyUpdateOne { + if v != nil { + _u.SetActionType(*v) + } + return _u +} + +// SetPauseMinutes sets the "pause_minutes" field. +func (_u *SchedulingPolicyUpdateOne) SetPauseMinutes(v int) *SchedulingPolicyUpdateOne { + _u.mutation.ResetPauseMinutes() + _u.mutation.SetPauseMinutes(v) + return _u +} + +// SetNillablePauseMinutes sets the "pause_minutes" field if the given value is not nil. +func (_u *SchedulingPolicyUpdateOne) SetNillablePauseMinutes(v *int) *SchedulingPolicyUpdateOne { + if v != nil { + _u.SetPauseMinutes(*v) + } + return _u +} + +// AddPauseMinutes adds value to the "pause_minutes" field. +func (_u *SchedulingPolicyUpdateOne) AddPauseMinutes(v int) *SchedulingPolicyUpdateOne { + _u.mutation.AddPauseMinutes(v) + return _u +} + +// SetPriorityDelta sets the "priority_delta" field. +func (_u *SchedulingPolicyUpdateOne) SetPriorityDelta(v int) *SchedulingPolicyUpdateOne { + _u.mutation.ResetPriorityDelta() + _u.mutation.SetPriorityDelta(v) + return _u +} + +// SetNillablePriorityDelta sets the "priority_delta" field if the given value is not nil. +func (_u *SchedulingPolicyUpdateOne) SetNillablePriorityDelta(v *int) *SchedulingPolicyUpdateOne { + if v != nil { + _u.SetPriorityDelta(*v) + } + return _u +} + +// AddPriorityDelta adds value to the "priority_delta" field. +func (_u *SchedulingPolicyUpdateOne) AddPriorityDelta(v int) *SchedulingPolicyUpdateOne { + _u.mutation.AddPriorityDelta(v) + return _u +} + +// SetRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field. +func (_u *SchedulingPolicyUpdateOne) SetRecoverConsecutiveSuccesses(v int) *SchedulingPolicyUpdateOne { + _u.mutation.ResetRecoverConsecutiveSuccesses() + _u.mutation.SetRecoverConsecutiveSuccesses(v) + return _u +} + +// SetNillableRecoverConsecutiveSuccesses sets the "recover_consecutive_successes" field if the given value is not nil. +func (_u *SchedulingPolicyUpdateOne) SetNillableRecoverConsecutiveSuccesses(v *int) *SchedulingPolicyUpdateOne { + if v != nil { + _u.SetRecoverConsecutiveSuccesses(*v) + } + return _u +} + +// AddRecoverConsecutiveSuccesses adds value to the "recover_consecutive_successes" field. +func (_u *SchedulingPolicyUpdateOne) AddRecoverConsecutiveSuccesses(v int) *SchedulingPolicyUpdateOne { + _u.mutation.AddRecoverConsecutiveSuccesses(v) + return _u +} + +// SetCooldownMinutes sets the "cooldown_minutes" field. +func (_u *SchedulingPolicyUpdateOne) SetCooldownMinutes(v int) *SchedulingPolicyUpdateOne { + _u.mutation.ResetCooldownMinutes() + _u.mutation.SetCooldownMinutes(v) + return _u +} + +// SetNillableCooldownMinutes sets the "cooldown_minutes" field if the given value is not nil. +func (_u *SchedulingPolicyUpdateOne) SetNillableCooldownMinutes(v *int) *SchedulingPolicyUpdateOne { + if v != nil { + _u.SetCooldownMinutes(*v) + } + return _u +} + +// AddCooldownMinutes adds value to the "cooldown_minutes" field. +func (_u *SchedulingPolicyUpdateOne) AddCooldownMinutes(v int) *SchedulingPolicyUpdateOne { + _u.mutation.AddCooldownMinutes(v) + return _u +} + +// Mutation returns the SchedulingPolicyMutation object of the builder. +func (_u *SchedulingPolicyUpdateOne) Mutation() *SchedulingPolicyMutation { + return _u.mutation +} + +// Where appends a list predicates to the SchedulingPolicyUpdate builder. +func (_u *SchedulingPolicyUpdateOne) Where(ps ...predicate.SchedulingPolicy) *SchedulingPolicyUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *SchedulingPolicyUpdateOne) Select(field string, fields ...string) *SchedulingPolicyUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated SchedulingPolicy entity. +func (_u *SchedulingPolicyUpdateOne) Save(ctx context.Context) (*SchedulingPolicy, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SchedulingPolicyUpdateOne) SaveX(ctx context.Context) *SchedulingPolicy { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *SchedulingPolicyUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SchedulingPolicyUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *SchedulingPolicyUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := schedulingpolicy.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SchedulingPolicyUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := schedulingpolicy.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.name": %w`, err)} + } + } + if v, ok := _u.mutation.TriggerConsecutiveFailures(); ok { + if err := schedulingpolicy.TriggerConsecutiveFailuresValidator(v); err != nil { + return &ValidationError{Name: "trigger_consecutive_failures", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.trigger_consecutive_failures": %w`, err)} + } + } + if v, ok := _u.mutation.TriggerLatencyMs(); ok { + if err := schedulingpolicy.TriggerLatencyMsValidator(v); err != nil { + return &ValidationError{Name: "trigger_latency_ms", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.trigger_latency_ms": %w`, err)} + } + } + if v, ok := _u.mutation.ActionType(); ok { + if err := schedulingpolicy.ActionTypeValidator(v); err != nil { + return &ValidationError{Name: "action_type", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.action_type": %w`, err)} + } + } + if v, ok := _u.mutation.PauseMinutes(); ok { + if err := schedulingpolicy.PauseMinutesValidator(v); err != nil { + return &ValidationError{Name: "pause_minutes", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.pause_minutes": %w`, err)} + } + } + if v, ok := _u.mutation.PriorityDelta(); ok { + if err := schedulingpolicy.PriorityDeltaValidator(v); err != nil { + return &ValidationError{Name: "priority_delta", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.priority_delta": %w`, err)} + } + } + if v, ok := _u.mutation.RecoverConsecutiveSuccesses(); ok { + if err := schedulingpolicy.RecoverConsecutiveSuccessesValidator(v); err != nil { + return &ValidationError{Name: "recover_consecutive_successes", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.recover_consecutive_successes": %w`, err)} + } + } + if v, ok := _u.mutation.CooldownMinutes(); ok { + if err := schedulingpolicy.CooldownMinutesValidator(v); err != nil { + return &ValidationError{Name: "cooldown_minutes", err: fmt.Errorf(`ent: validator failed for field "SchedulingPolicy.cooldown_minutes": %w`, err)} + } + } + return nil +} + +func (_u *SchedulingPolicyUpdateOne) sqlSave(ctx context.Context) (_node *SchedulingPolicy, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(schedulingpolicy.Table, schedulingpolicy.Columns, sqlgraph.NewFieldSpec(schedulingpolicy.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "SchedulingPolicy.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, schedulingpolicy.FieldID) + for _, f := range fields { + if !schedulingpolicy.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != schedulingpolicy.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(schedulingpolicy.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(schedulingpolicy.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Enabled(); ok { + _spec.SetField(schedulingpolicy.FieldEnabled, field.TypeBool, value) + } + if value, ok := _u.mutation.MonitorID(); ok { + _spec.SetField(schedulingpolicy.FieldMonitorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedMonitorID(); ok { + _spec.AddField(schedulingpolicy.FieldMonitorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AccountIds(); ok { + _spec.SetField(schedulingpolicy.FieldAccountIds, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedAccountIds(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, schedulingpolicy.FieldAccountIds, value) + }) + } + if value, ok := _u.mutation.TriggerConsecutiveFailures(); ok { + _spec.SetField(schedulingpolicy.FieldTriggerConsecutiveFailures, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedTriggerConsecutiveFailures(); ok { + _spec.AddField(schedulingpolicy.FieldTriggerConsecutiveFailures, field.TypeInt, value) + } + if value, ok := _u.mutation.TriggerLatencyMs(); ok { + _spec.SetField(schedulingpolicy.FieldTriggerLatencyMs, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedTriggerLatencyMs(); ok { + _spec.AddField(schedulingpolicy.FieldTriggerLatencyMs, field.TypeInt, value) + } + if value, ok := _u.mutation.ActionType(); ok { + _spec.SetField(schedulingpolicy.FieldActionType, field.TypeString, value) + } + if value, ok := _u.mutation.PauseMinutes(); ok { + _spec.SetField(schedulingpolicy.FieldPauseMinutes, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedPauseMinutes(); ok { + _spec.AddField(schedulingpolicy.FieldPauseMinutes, field.TypeInt, value) + } + if value, ok := _u.mutation.PriorityDelta(); ok { + _spec.SetField(schedulingpolicy.FieldPriorityDelta, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedPriorityDelta(); ok { + _spec.AddField(schedulingpolicy.FieldPriorityDelta, field.TypeInt, value) + } + if value, ok := _u.mutation.RecoverConsecutiveSuccesses(); ok { + _spec.SetField(schedulingpolicy.FieldRecoverConsecutiveSuccesses, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedRecoverConsecutiveSuccesses(); ok { + _spec.AddField(schedulingpolicy.FieldRecoverConsecutiveSuccesses, field.TypeInt, value) + } + if value, ok := _u.mutation.CooldownMinutes(); ok { + _spec.SetField(schedulingpolicy.FieldCooldownMinutes, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedCooldownMinutes(); ok { + _spec.AddField(schedulingpolicy.FieldCooldownMinutes, field.TypeInt, value) + } + _node = &SchedulingPolicy{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{schedulingpolicy.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/ent/schema/scheduling_action.go b/backend/ent/schema/scheduling_action.go new file mode 100644 index 000000000000..5b56cc16ce04 --- /dev/null +++ b/backend/ent/schema/scheduling_action.go @@ -0,0 +1,51 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// SchedulingAction holds the schema definition for the SchedulingAction entity. +// 调度策略动作审计:记录每次策略触发/恢复对账号做了什么,以及恢复所需的原始状态。 +type SchedulingAction struct { + ent.Schema +} + +func (SchedulingAction) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "scheduling_actions"}, + } +} + +func (SchedulingAction) Fields() []ent.Field { + return []ent.Field{ + field.Int64("policy_id"), + field.Int64("account_id"), + field.Int64("monitor_id"), + field.String("action"). + MaxLen(32). + Comment("pause / deprioritize / recover"), + field.String("reason"). + Default(""). + MaxLen(500), + field.Int("original_priority"). + Default(0). + Comment("deprioritize 动作执行前的账号优先级,恢复时还原"), + field.Bool("restored"). + Default(false). + Comment("该动作是否已被恢复(recover 动作本身恒为 true)"), + field.Time("created_at"). + Immutable(). + Annotations(entsql.Default("CURRENT_TIMESTAMP")), + } +} + +func (SchedulingAction) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("policy_id", "created_at"), + index.Fields("account_id", "restored"), + } +} diff --git a/backend/ent/schema/scheduling_policy.go b/backend/ent/schema/scheduling_policy.go new file mode 100644 index 000000000000..458b33fc033a --- /dev/null +++ b/backend/ent/schema/scheduling_policy.go @@ -0,0 +1,80 @@ +package schema + +import ( + "github.com/Wei-Shaw/sub2api/ent/schema/mixins" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// SchedulingPolicy holds the schema definition for the SchedulingPolicy entity. +// 渠道调度策略:将渠道监控(channel_monitors)的检测结果与账号调度动作联动。 +// 触发条件满足时对目标账号执行临时停用/降低优先级,恢复条件满足后自动还原。 +type SchedulingPolicy struct { + ent.Schema +} + +func (SchedulingPolicy) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "scheduling_policies"}, + } +} + +func (SchedulingPolicy) Mixin() []ent.Mixin { + return []ent.Mixin{ + mixins.TimeMixin{}, + } +} + +func (SchedulingPolicy) Fields() []ent.Field { + return []ent.Field{ + field.String("name"). + NotEmpty(). + MaxLen(100), + field.Bool("enabled"). + Default(true), + field.Int64("monitor_id"). + Comment("条件源:channel_monitors.id,监控被删除时策略停摆但保留配置"), + field.JSON("account_ids", []int64{}). + Default([]int64{}). + Comment("动作目标账号 ID 列表"), + field.Int("trigger_consecutive_failures"). + Default(3). + Range(1, 100). + Comment("连续失败 N 次后触发(failed/error 或延迟超阈值均计为失败)"), + field.Int("trigger_latency_ms"). + Default(0). + Range(0, 600000). + Comment("延迟阈值(毫秒),检测延迟超过该值计为一次失败;0 表示不启用延迟条件"), + field.String("action_type"). + Default("pause"). + MaxLen(32). + Comment("触发动作:pause(临时停用)或 deprioritize(降低优先级)"), + field.Int("pause_minutes"). + Default(0). + Range(0, 10080). + Comment("pause 动作的停用时长(分钟);0 表示停用至恢复条件满足"), + field.Int("priority_delta"). + Default(10). + Range(1, 1000). + Comment("deprioritize 动作在原优先级上增加的数值(数值越大优先级越低)"), + field.Int("recover_consecutive_successes"). + Default(2). + Range(0, 100). + Comment("连续成功 N 次后自动恢复;0 表示不自动恢复"), + field.Int("cooldown_minutes"). + Default(10). + Range(0, 1440). + Comment("两次触发之间的最小间隔(分钟),防止抖动反复触发"), + } +} + +func (SchedulingPolicy) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("monitor_id"), + index.Fields("enabled"), + } +} diff --git a/backend/ent/tx.go b/backend/ent/tx.go index 6de2c2b63b72..e602317a0610 100644 --- a/backend/ent/tx.go +++ b/backend/ent/tx.go @@ -66,6 +66,10 @@ type Tx struct { Proxy *ProxyClient // RedeemCode is the client for interacting with the RedeemCode builders. RedeemCode *RedeemCodeClient + // SchedulingAction is the client for interacting with the SchedulingAction builders. + SchedulingAction *SchedulingActionClient + // SchedulingPolicy is the client for interacting with the SchedulingPolicy builders. + SchedulingPolicy *SchedulingPolicyClient // SecuritySecret is the client for interacting with the SecuritySecret builders. SecuritySecret *SecuritySecretClient // Setting is the client for interacting with the Setting builders. @@ -247,6 +251,8 @@ func (tx *Tx) init() { tx.PromoCodeUsage = NewPromoCodeUsageClient(tx.config) tx.Proxy = NewProxyClient(tx.config) tx.RedeemCode = NewRedeemCodeClient(tx.config) + tx.SchedulingAction = NewSchedulingActionClient(tx.config) + tx.SchedulingPolicy = NewSchedulingPolicyClient(tx.config) tx.SecuritySecret = NewSecuritySecretClient(tx.config) tx.Setting = NewSettingClient(tx.config) tx.SubscriptionPlan = NewSubscriptionPlanClient(tx.config) diff --git a/backend/internal/handler/admin/scheduling_policy_handler.go b/backend/internal/handler/admin/scheduling_policy_handler.go new file mode 100644 index 000000000000..ffdd3f43cbd3 --- /dev/null +++ b/backend/internal/handler/admin/scheduling_policy_handler.go @@ -0,0 +1,247 @@ +package admin + +import ( + "strconv" + "strings" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/service" + + "github.com/gin-gonic/gin" +) + +// SchedulingPolicyHandler 渠道调度策略管理后台 handler。 +type SchedulingPolicyHandler struct { + policyService *service.SchedulingPolicyService +} + +// NewSchedulingPolicyHandler 创建 handler。 +func NewSchedulingPolicyHandler(policyService *service.SchedulingPolicyService) *SchedulingPolicyHandler { + return &SchedulingPolicyHandler{policyService: policyService} +} + +// --- Request / Response --- + +type schedulingPolicyRequest struct { + Name string `json:"name" binding:"required,max=100"` + Enabled *bool `json:"enabled"` + MonitorID int64 `json:"monitor_id" binding:"required,min=1"` + AccountIDs []int64 `json:"account_ids" binding:"required,min=1"` + TriggerConsecutiveFailures int `json:"trigger_consecutive_failures" binding:"required,min=1,max=100"` + TriggerLatencyMs int `json:"trigger_latency_ms" binding:"omitempty,min=0,max=600000"` + ActionType string `json:"action_type" binding:"required,oneof=pause deprioritize"` + PauseMinutes int `json:"pause_minutes" binding:"omitempty,min=0,max=10080"` + PriorityDelta int `json:"priority_delta" binding:"omitempty,min=1,max=1000"` + RecoverConsecutiveSuccesses int `json:"recover_consecutive_successes" binding:"omitempty,min=0,max=100"` + CooldownMinutes int `json:"cooldown_minutes" binding:"omitempty,min=0,max=1440"` +} + +type schedulingPolicyResponse struct { + ID int64 `json:"id"` + Name string `json:"name"` + Enabled bool `json:"enabled"` + MonitorID int64 `json:"monitor_id"` + AccountIDs []int64 `json:"account_ids"` + TriggerConsecutiveFailures int `json:"trigger_consecutive_failures"` + TriggerLatencyMs int `json:"trigger_latency_ms"` + ActionType string `json:"action_type"` + PauseMinutes int `json:"pause_minutes"` + PriorityDelta int `json:"priority_delta"` + RecoverConsecutiveSuccesses int `json:"recover_consecutive_successes"` + CooldownMinutes int `json:"cooldown_minutes"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type schedulingActionResponse struct { + ID int64 `json:"id"` + PolicyID int64 `json:"policy_id"` + AccountID int64 `json:"account_id"` + MonitorID int64 `json:"monitor_id"` + Action string `json:"action"` + Reason string `json:"reason"` + OriginalPriority int `json:"original_priority"` + Restored bool `json:"restored"` + CreatedAt string `json:"created_at"` +} + +func schedulingPolicyToResponse(p *service.SchedulingPolicy) *schedulingPolicyResponse { + if p == nil { + return nil + } + accountIDs := p.AccountIDs + if accountIDs == nil { + accountIDs = []int64{} + } + return &schedulingPolicyResponse{ + ID: p.ID, + Name: p.Name, + Enabled: p.Enabled, + MonitorID: p.MonitorID, + AccountIDs: accountIDs, + TriggerConsecutiveFailures: p.TriggerConsecutiveFailures, + TriggerLatencyMs: p.TriggerLatencyMs, + ActionType: p.ActionType, + PauseMinutes: p.PauseMinutes, + PriorityDelta: p.PriorityDelta, + RecoverConsecutiveSuccesses: p.RecoverConsecutiveSuccesses, + CooldownMinutes: p.CooldownMinutes, + CreatedAt: p.CreatedAt.UTC().Format(time.RFC3339), + UpdatedAt: p.UpdatedAt.UTC().Format(time.RFC3339), + } +} + +func schedulingActionToResponse(a *service.SchedulingActionRecord) *schedulingActionResponse { + return &schedulingActionResponse{ + ID: a.ID, + PolicyID: a.PolicyID, + AccountID: a.AccountID, + MonitorID: a.MonitorID, + Action: a.Action, + Reason: a.Reason, + OriginalPriority: a.OriginalPriority, + Restored: a.Restored, + CreatedAt: a.CreatedAt.UTC().Format(time.RFC3339), + } +} + +func requestToSchedulingPolicy(req *schedulingPolicyRequest) *service.SchedulingPolicy { + enabled := true + if req.Enabled != nil { + enabled = *req.Enabled + } + priorityDelta := req.PriorityDelta + if priorityDelta == 0 { + priorityDelta = 10 + } + return &service.SchedulingPolicy{ + Name: req.Name, + Enabled: enabled, + MonitorID: req.MonitorID, + AccountIDs: req.AccountIDs, + TriggerConsecutiveFailures: req.TriggerConsecutiveFailures, + TriggerLatencyMs: req.TriggerLatencyMs, + ActionType: req.ActionType, + PauseMinutes: req.PauseMinutes, + PriorityDelta: priorityDelta, + RecoverConsecutiveSuccesses: req.RecoverConsecutiveSuccesses, + CooldownMinutes: req.CooldownMinutes, + } +} + +func parseSchedulingPolicyID(c *gin.Context) (int64, bool) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id <= 0 { + response.ErrorFrom(c, infraerrors.BadRequest("INVALID_POLICY_ID", "invalid policy id")) + return 0, false + } + return id, true +} + +// --- Handlers --- + +// List GET /admin/scheduling-policies +func (h *SchedulingPolicyHandler) List(c *gin.Context) { + page, pageSize := response.ParsePagination(c) + items, total, err := h.policyService.List(c.Request.Context(), service.SchedulingPolicyListParams{ + Page: page, + PageSize: pageSize, + Enabled: parseListEnabled(c.Query("enabled")), + Search: strings.TrimSpace(c.Query("search")), + }) + if err != nil { + response.ErrorFrom(c, err) + return + } + out := make([]*schedulingPolicyResponse, 0, len(items)) + for _, p := range items { + out = append(out, schedulingPolicyToResponse(p)) + } + response.Paginated(c, out, total, page, pageSize) +} + +// Get GET /admin/scheduling-policies/:id +func (h *SchedulingPolicyHandler) Get(c *gin.Context) { + id, ok := parseSchedulingPolicyID(c) + if !ok { + return + } + p, err := h.policyService.Get(c.Request.Context(), id) + if err != nil { + response.ErrorFrom(c, err) + return + } + response.Success(c, schedulingPolicyToResponse(p)) +} + +// Create POST /admin/scheduling-policies +func (h *SchedulingPolicyHandler) Create(c *gin.Context) { + var req schedulingPolicyRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorFrom(c, infraerrors.BadRequest("VALIDATION_ERROR", err.Error())) + return + } + p := requestToSchedulingPolicy(&req) + if err := h.policyService.Create(c.Request.Context(), p); err != nil { + response.ErrorFrom(c, infraerrors.BadRequest("VALIDATION_ERROR", err.Error())) + return + } + response.Success(c, schedulingPolicyToResponse(p)) +} + +// Update PUT /admin/scheduling-policies/:id +func (h *SchedulingPolicyHandler) Update(c *gin.Context) { + id, ok := parseSchedulingPolicyID(c) + if !ok { + return + } + var req schedulingPolicyRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.ErrorFrom(c, infraerrors.BadRequest("VALIDATION_ERROR", err.Error())) + return + } + p := requestToSchedulingPolicy(&req) + p.ID = id + if err := h.policyService.Update(c.Request.Context(), p); err != nil { + response.ErrorFrom(c, err) + return + } + response.Success(c, schedulingPolicyToResponse(p)) +} + +// Delete DELETE /admin/scheduling-policies/:id +func (h *SchedulingPolicyHandler) Delete(c *gin.Context) { + id, ok := parseSchedulingPolicyID(c) + if !ok { + return + } + if err := h.policyService.Delete(c.Request.Context(), id); err != nil { + response.ErrorFrom(c, err) + return + } + response.Success(c, gin.H{"deleted": true}) +} + +// Actions GET /admin/scheduling-policies/actions +func (h *SchedulingPolicyHandler) Actions(c *gin.Context) { + page, pageSize := response.ParsePagination(c) + policyID, _ := strconv.ParseInt(c.Query("policy_id"), 10, 64) + accountID, _ := strconv.ParseInt(c.Query("account_id"), 10, 64) + items, total, err := h.policyService.ListActions(c.Request.Context(), service.SchedulingActionListParams{ + Page: page, + PageSize: pageSize, + PolicyID: policyID, + AccountID: accountID, + }) + if err != nil { + response.ErrorFrom(c, err) + return + } + out := make([]*schedulingActionResponse, 0, len(items)) + for _, a := range items { + out = append(out, schedulingActionToResponse(a)) + } + response.Paginated(c, out, total, page, pageSize) +} diff --git a/backend/internal/handler/handler.go b/backend/internal/handler/handler.go index 58c524889cb9..5b12d82e975b 100644 --- a/backend/internal/handler/handler.go +++ b/backend/internal/handler/handler.go @@ -34,6 +34,7 @@ type AdminHandlers struct { Channel *admin.ChannelHandler ChannelMonitor *admin.ChannelMonitorHandler ChannelMonitorTemplate *admin.ChannelMonitorRequestTemplateHandler + SchedulingPolicy *admin.SchedulingPolicyHandler ContentModeration *admin.ContentModerationHandler Payment *admin.PaymentHandler Affiliate *admin.AffiliateHandler diff --git a/backend/internal/handler/model_plaza_handler.go b/backend/internal/handler/model_plaza_handler.go new file mode 100644 index 000000000000..1811d3f195f0 --- /dev/null +++ b/backend/internal/handler/model_plaza_handler.go @@ -0,0 +1,146 @@ +package handler + +import ( + "sort" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + + "github.com/gin-gonic/gin" +) + +// 模型广场:以「模型」为中心聚合所有活跃渠道的定价与分组倍率,供用户端模型广场页展示。 +// +// 数据完全复用 ChannelService.ListAvailable 的展示链路(含 LiteLLM 全局价格回落), +// 不触碰真实计费逻辑。可见性与「可用渠道」页保持一致:按用户可访问分组过滤, +// 受 available-channels 功能开关控制(关闭时返回空列表), +// 用户专属倍率由前端走 /groups/rates 合并。 + +// modelPlazaEntry 模型广场单个模型条目。 +type modelPlazaEntry struct { + Name string `json:"name"` + Platform string `json:"platform"` + Pricing *userSupportedModelPricing `json:"pricing"` + Groups []userAvailableGroup `json:"groups"` +} + +// ListModelPlaza 登录版模型广场:按当前用户可访问分组过滤。 +// GET /api/v1/model-plaza +func (h *AvailableChannelHandler) ListModelPlaza(c *gin.Context) { + subject, ok := middleware.GetAuthSubjectFromContext(c) + if !ok { + response.Unauthorized(c, "User not authenticated") + return + } + if !h.featureEnabled(c) { + response.Success(c, []modelPlazaEntry{}) + return + } + + userGroups, err := h.apiKeyService.GetAvailableGroups(c.Request.Context(), subject.UserID) + if err != nil { + response.ErrorFrom(c, err) + return + } + allowedGroupIDs := make(map[int64]struct{}, len(userGroups)) + for i := range userGroups { + allowedGroupIDs[userGroups[i].ID] = struct{}{} + } + + channels, err := h.channelService.ListAvailable(c.Request.Context()) + if err != nil { + response.ErrorFrom(c, err) + return + } + response.Success(c, buildModelPlaza(channels, allowedGroupIDs)) +} + +// buildModelPlaza 把渠道视图聚合为模型为中心的条目列表,仅保留 allowedGroupIDs 中的分组。 +// 同名同平台模型跨渠道合并:定价取首个非空(各渠道未配置时均已回落到全局 +// LiteLLM 数据,展示上等价),分组按 ID 去重后并集。 +func buildModelPlaza( + channels []service.AvailableChannel, + allowedGroupIDs map[int64]struct{}, +) []modelPlazaEntry { + type plazaKey struct{ name, platform string } + byKey := make(map[plazaKey]*modelPlazaEntry) + seenGroups := make(map[plazaKey]map[int64]struct{}) + + for i := range channels { + ch := &channels[i] + if ch.Status != service.StatusActive { + continue + } + + groupsByPlatform := make(map[string][]userAvailableGroup, 4) + for _, g := range ch.Groups { + if g.Platform == "" { + continue + } + if _, ok := allowedGroupIDs[g.ID]; !ok { + continue + } + groupsByPlatform[g.Platform] = append(groupsByPlatform[g.Platform], userAvailableGroup{ + ID: g.ID, + Name: g.Name, + Platform: g.Platform, + SubscriptionType: g.SubscriptionType, + RateMultiplier: g.RateMultiplier, + PeakRateEnabled: g.PeakRateEnabled, + PeakStart: g.PeakStart, + PeakEnd: g.PeakEnd, + PeakRateMultiplier: g.PeakRateMultiplier, + IsExclusive: g.IsExclusive, + }) + } + if len(groupsByPlatform) == 0 { + continue + } + + for j := range ch.SupportedModels { + m := &ch.SupportedModels[j] + platformGroups := groupsByPlatform[m.Platform] + if len(platformGroups) == 0 { + continue + } + key := plazaKey{name: m.Name, platform: m.Platform} + entry, ok := byKey[key] + if !ok { + entry = &modelPlazaEntry{ + Name: m.Name, + Platform: m.Platform, + Pricing: toUserPricing(m.Pricing), + } + byKey[key] = entry + seenGroups[key] = make(map[int64]struct{}) + } + if entry.Pricing == nil && m.Pricing != nil { + entry.Pricing = toUserPricing(m.Pricing) + } + for _, g := range platformGroups { + if _, dup := seenGroups[key][g.ID]; dup { + continue + } + seenGroups[key][g.ID] = struct{}{} + entry.Groups = append(entry.Groups, g) + } + } + } + + out := make([]modelPlazaEntry, 0, len(byKey)) + for _, entry := range byKey { + sort.SliceStable(entry.Groups, func(i, j int) bool { + return entry.Groups[i].Name < entry.Groups[j].Name + }) + out = append(out, *entry) + } + sort.SliceStable(out, func(i, j int) bool { + if out[i].Platform != out[j].Platform { + return out[i].Platform < out[j].Platform + } + return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) + }) + return out +} diff --git a/backend/internal/handler/model_plaza_handler_test.go b/backend/internal/handler/model_plaza_handler_test.go new file mode 100644 index 000000000000..3b79428db1c9 --- /dev/null +++ b/backend/internal/handler/model_plaza_handler_test.go @@ -0,0 +1,100 @@ +//go:build unit + +package handler + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func plazaTestChannels() []service.AvailableChannel { + in := 1e-6 + out := 5e-6 + return []service.AvailableChannel{ + { + ID: 1, + Name: "channel-a", + Status: service.StatusActive, + Groups: []service.AvailableGroupRef{ + {ID: 10, Name: "public-claude", Platform: "anthropic", RateMultiplier: 1.0, IsExclusive: false}, + {ID: 11, Name: "vip-claude", Platform: "anthropic", RateMultiplier: 0.8, IsExclusive: true}, + }, + SupportedModels: []service.SupportedModel{ + {Name: "claude-sonnet-4-5", Platform: "anthropic", Pricing: &service.ChannelModelPricing{InputPrice: &in, OutputPrice: &out}}, + }, + }, + { + ID: 2, + Name: "channel-b", + Status: service.StatusActive, + Groups: []service.AvailableGroupRef{ + {ID: 10, Name: "public-claude", Platform: "anthropic", RateMultiplier: 1.0, IsExclusive: false}, + {ID: 20, Name: "public-openai", Platform: "openai", RateMultiplier: 1.5, IsExclusive: false}, + }, + SupportedModels: []service.SupportedModel{ + {Name: "claude-sonnet-4-5", Platform: "anthropic", Pricing: &service.ChannelModelPricing{InputPrice: &in, OutputPrice: &out}}, + {Name: "gpt-5", Platform: "openai", Pricing: &service.ChannelModelPricing{InputPrice: &in, OutputPrice: &out}}, + }, + }, + { + ID: 3, + Name: "channel-disabled", + Status: "disabled", + Groups: []service.AvailableGroupRef{ + {ID: 30, Name: "public-gemini", Platform: "gemini", RateMultiplier: 1.0, IsExclusive: false}, + }, + SupportedModels: []service.SupportedModel{ + {Name: "gemini-2.5-pro", Platform: "gemini"}, + }, + }, + } +} + +func TestBuildModelPlaza_MergesChannelsAndDedupesGroups(t *testing.T) { + allowed := map[int64]struct{}{10: {}, 20: {}} + entries := buildModelPlaza(plazaTestChannels(), allowed) + + // 停用渠道的 gemini 模型不出现 + require.Len(t, entries, 2) + // 排序:platform 字母序 anthropic < openai + require.Equal(t, "claude-sonnet-4-5", entries[0].Name) + require.Equal(t, "gpt-5", entries[1].Name) + + // claude 模型:跨渠道合并,分组按 ID 去重,不可访问的分组(11)被过滤 + claude := entries[0] + require.Len(t, claude.Groups, 1) + require.Equal(t, int64(10), claude.Groups[0].ID) + require.NotNil(t, claude.Pricing) + require.NotNil(t, claude.Pricing.InputPrice) +} + +func TestBuildModelPlaza_UserFilterByAllowedGroups(t *testing.T) { + allowed := map[int64]struct{}{11: {}} // 只可访问专属分组 + entries := buildModelPlaza(plazaTestChannels(), allowed) + + require.Len(t, entries, 1) + require.Equal(t, "claude-sonnet-4-5", entries[0].Name) + require.Len(t, entries[0].Groups, 1) + require.Equal(t, int64(11), entries[0].Groups[0].ID) + require.True(t, entries[0].Groups[0].IsExclusive) +} + +func TestModelPlaza_Unauthenticated401(t *testing.T) { + gin.SetMode(gin.TestMode) + h := &AvailableChannelHandler{} // 401 路径不会触达 service 依赖 + + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/model-plaza", nil) + + h.ListModelPlaza(c) + require.Equal(t, http.StatusUnauthorized, w.Code) +} + + diff --git a/backend/internal/handler/wire.go b/backend/internal/handler/wire.go index cfbb72554ca2..f5fe344dfd8b 100644 --- a/backend/internal/handler/wire.go +++ b/backend/internal/handler/wire.go @@ -37,6 +37,7 @@ func ProvideAdminHandlers( channelHandler *admin.ChannelHandler, channelMonitorHandler *admin.ChannelMonitorHandler, channelMonitorTemplateHandler *admin.ChannelMonitorRequestTemplateHandler, + schedulingPolicyHandler *admin.SchedulingPolicyHandler, contentModerationHandler *admin.ContentModerationHandler, paymentHandler *admin.PaymentHandler, affiliateHandler *admin.AffiliateHandler, @@ -71,6 +72,7 @@ func ProvideAdminHandlers( Channel: channelHandler, ChannelMonitor: channelMonitorHandler, ChannelMonitorTemplate: channelMonitorTemplateHandler, + SchedulingPolicy: schedulingPolicyHandler, ContentModeration: contentModerationHandler, Payment: paymentHandler, Affiliate: affiliateHandler, @@ -188,6 +190,7 @@ var ProviderSet = wire.NewSet( admin.NewScheduledTestHandler, admin.NewChannelHandler, admin.NewChannelMonitorHandler, + admin.NewSchedulingPolicyHandler, admin.NewChannelMonitorRequestTemplateHandler, admin.NewContentModerationHandler, admin.NewPaymentHandler, diff --git a/backend/internal/repository/scheduling_policy_repo.go b/backend/internal/repository/scheduling_policy_repo.go new file mode 100644 index 000000000000..16b263ef2d88 --- /dev/null +++ b/backend/internal/repository/scheduling_policy_repo.go @@ -0,0 +1,276 @@ +package repository + +import ( + "context" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/ent/schedulingaction" + "github.com/Wei-Shaw/sub2api/ent/schedulingpolicy" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// schedulingPolicyRepository 实现 service.SchedulingPolicyRepository。 +type schedulingPolicyRepository struct { + client *dbent.Client +} + +// NewSchedulingPolicyRepository 创建仓储实例。 +func NewSchedulingPolicyRepository(client *dbent.Client) service.SchedulingPolicyRepository { + return &schedulingPolicyRepository{client: client} +} + +// ---------- 策略 CRUD ---------- + +func (r *schedulingPolicyRepository) Create(ctx context.Context, p *service.SchedulingPolicy) error { + client := clientFromContext(ctx, r.client) + created, err := client.SchedulingPolicy.Create(). + SetName(p.Name). + SetEnabled(p.Enabled). + SetMonitorID(p.MonitorID). + SetAccountIds(emptyInt64SliceIfNil(p.AccountIDs)). + SetTriggerConsecutiveFailures(p.TriggerConsecutiveFailures). + SetTriggerLatencyMs(p.TriggerLatencyMs). + SetActionType(p.ActionType). + SetPauseMinutes(p.PauseMinutes). + SetPriorityDelta(p.PriorityDelta). + SetRecoverConsecutiveSuccesses(p.RecoverConsecutiveSuccesses). + SetCooldownMinutes(p.CooldownMinutes). + Save(ctx) + if err != nil { + return err + } + *p = *schedulingPolicyFromEnt(created) + return nil +} + +func (r *schedulingPolicyRepository) GetByID(ctx context.Context, id int64) (*service.SchedulingPolicy, error) { + client := clientFromContext(ctx, r.client) + found, err := client.SchedulingPolicy.Get(ctx, id) + if err != nil { + if dbent.IsNotFound(err) { + return nil, service.ErrSchedulingPolicyNotFound + } + return nil, err + } + return schedulingPolicyFromEnt(found), nil +} + +func (r *schedulingPolicyRepository) Update(ctx context.Context, p *service.SchedulingPolicy) error { + client := clientFromContext(ctx, r.client) + updated, err := client.SchedulingPolicy.UpdateOneID(p.ID). + SetName(p.Name). + SetEnabled(p.Enabled). + SetMonitorID(p.MonitorID). + SetAccountIds(emptyInt64SliceIfNil(p.AccountIDs)). + SetTriggerConsecutiveFailures(p.TriggerConsecutiveFailures). + SetTriggerLatencyMs(p.TriggerLatencyMs). + SetActionType(p.ActionType). + SetPauseMinutes(p.PauseMinutes). + SetPriorityDelta(p.PriorityDelta). + SetRecoverConsecutiveSuccesses(p.RecoverConsecutiveSuccesses). + SetCooldownMinutes(p.CooldownMinutes). + Save(ctx) + if err != nil { + if dbent.IsNotFound(err) { + return service.ErrSchedulingPolicyNotFound + } + return err + } + *p = *schedulingPolicyFromEnt(updated) + return nil +} + +func (r *schedulingPolicyRepository) Delete(ctx context.Context, id int64) error { + client := clientFromContext(ctx, r.client) + if err := client.SchedulingPolicy.DeleteOneID(id).Exec(ctx); err != nil { + if dbent.IsNotFound(err) { + return service.ErrSchedulingPolicyNotFound + } + return err + } + return nil +} + +func (r *schedulingPolicyRepository) List(ctx context.Context, params service.SchedulingPolicyListParams) ([]*service.SchedulingPolicy, int64, error) { + client := clientFromContext(ctx, r.client) + q := client.SchedulingPolicy.Query() + if params.Enabled != nil { + q = q.Where(schedulingpolicy.EnabledEQ(*params.Enabled)) + } + if params.Search != "" { + q = q.Where(schedulingpolicy.NameContainsFold(params.Search)) + } + total, err := q.Clone().Count(ctx) + if err != nil { + return nil, 0, err + } + rows, err := q. + Order(dbent.Desc(schedulingpolicy.FieldID)). + Offset((params.Page - 1) * params.PageSize). + Limit(params.PageSize). + All(ctx) + if err != nil { + return nil, 0, err + } + items := make([]*service.SchedulingPolicy, 0, len(rows)) + for _, row := range rows { + items = append(items, schedulingPolicyFromEnt(row)) + } + return items, int64(total), nil +} + +func (r *schedulingPolicyRepository) ListEnabledByMonitorID(ctx context.Context, monitorID int64) ([]*service.SchedulingPolicy, error) { + client := clientFromContext(ctx, r.client) + rows, err := client.SchedulingPolicy.Query(). + Where(schedulingpolicy.MonitorIDEQ(monitorID), schedulingpolicy.EnabledEQ(true)). + All(ctx) + if err != nil { + return nil, err + } + items := make([]*service.SchedulingPolicy, 0, len(rows)) + for _, row := range rows { + items = append(items, schedulingPolicyFromEnt(row)) + } + return items, nil +} + +// ---------- 动作审计 ---------- + +func (r *schedulingPolicyRepository) InsertAction(ctx context.Context, a *service.SchedulingActionRecord) error { + client := clientFromContext(ctx, r.client) + created, err := client.SchedulingAction.Create(). + SetPolicyID(a.PolicyID). + SetAccountID(a.AccountID). + SetMonitorID(a.MonitorID). + SetAction(a.Action). + SetReason(a.Reason). + SetOriginalPriority(a.OriginalPriority). + SetRestored(a.Restored). + Save(ctx) + if err != nil { + return err + } + *a = *schedulingActionFromEnt(created) + return nil +} + +func (r *schedulingPolicyRepository) ListActions(ctx context.Context, params service.SchedulingActionListParams) ([]*service.SchedulingActionRecord, int64, error) { + client := clientFromContext(ctx, r.client) + q := client.SchedulingAction.Query() + if params.PolicyID > 0 { + q = q.Where(schedulingaction.PolicyIDEQ(params.PolicyID)) + } + if params.AccountID > 0 { + q = q.Where(schedulingaction.AccountIDEQ(params.AccountID)) + } + total, err := q.Clone().Count(ctx) + if err != nil { + return nil, 0, err + } + rows, err := q. + Order(dbent.Desc(schedulingaction.FieldID)). + Offset((params.Page - 1) * params.PageSize). + Limit(params.PageSize). + All(ctx) + if err != nil { + return nil, 0, err + } + items := make([]*service.SchedulingActionRecord, 0, len(rows)) + for _, row := range rows { + items = append(items, schedulingActionFromEnt(row)) + } + return items, int64(total), nil +} + +func (r *schedulingPolicyRepository) ListUnrestoredActions(ctx context.Context, policyID int64) ([]*service.SchedulingActionRecord, error) { + client := clientFromContext(ctx, r.client) + rows, err := client.SchedulingAction.Query(). + Where( + schedulingaction.PolicyIDEQ(policyID), + schedulingaction.RestoredEQ(false), + schedulingaction.ActionNEQ(service.SchedulingActionRecover), + ). + All(ctx) + if err != nil { + return nil, err + } + items := make([]*service.SchedulingActionRecord, 0, len(rows)) + for _, row := range rows { + items = append(items, schedulingActionFromEnt(row)) + } + return items, nil +} + +func (r *schedulingPolicyRepository) MarkActionsRestored(ctx context.Context, ids []int64) error { + if len(ids) == 0 { + return nil + } + client := clientFromContext(ctx, r.client) + _, err := client.SchedulingAction.Update(). + Where(schedulingaction.IDIn(ids...)). + SetRestored(true). + Save(ctx) + return err +} + +func (r *schedulingPolicyRepository) LatestTriggerAt(ctx context.Context, policyID int64) (*time.Time, error) { + client := clientFromContext(ctx, r.client) + row, err := client.SchedulingAction.Query(). + Where( + schedulingaction.PolicyIDEQ(policyID), + schedulingaction.ActionNEQ(service.SchedulingActionRecover), + ). + Order(dbent.Desc(schedulingaction.FieldID)). + First(ctx) + if err != nil { + if dbent.IsNotFound(err) { + return nil, nil + } + return nil, err + } + t := row.CreatedAt + return &t, nil +} + +// ---------- 转换 ---------- + +func emptyInt64SliceIfNil(s []int64) []int64 { + if s == nil { + return []int64{} + } + return s +} + +func schedulingPolicyFromEnt(e *dbent.SchedulingPolicy) *service.SchedulingPolicy { + return &service.SchedulingPolicy{ + ID: e.ID, + Name: e.Name, + Enabled: e.Enabled, + MonitorID: e.MonitorID, + AccountIDs: e.AccountIds, + TriggerConsecutiveFailures: e.TriggerConsecutiveFailures, + TriggerLatencyMs: e.TriggerLatencyMs, + ActionType: e.ActionType, + PauseMinutes: e.PauseMinutes, + PriorityDelta: e.PriorityDelta, + RecoverConsecutiveSuccesses: e.RecoverConsecutiveSuccesses, + CooldownMinutes: e.CooldownMinutes, + CreatedAt: e.CreatedAt, + UpdatedAt: e.UpdatedAt, + } +} + +func schedulingActionFromEnt(e *dbent.SchedulingAction) *service.SchedulingActionRecord { + return &service.SchedulingActionRecord{ + ID: e.ID, + PolicyID: e.PolicyID, + AccountID: e.AccountID, + MonitorID: e.MonitorID, + Action: e.Action, + Reason: e.Reason, + OriginalPriority: e.OriginalPriority, + Restored: e.Restored, + CreatedAt: e.CreatedAt, + } +} diff --git a/backend/internal/repository/wire.go b/backend/internal/repository/wire.go index ec5078eac896..3922b8ccdc05 100644 --- a/backend/internal/repository/wire.go +++ b/backend/internal/repository/wire.go @@ -91,6 +91,7 @@ var ProviderSet = wire.NewSet( NewTLSFingerprintProfileRepository, NewChannelRepository, NewChannelMonitorRepository, + NewSchedulingPolicyRepository, NewChannelMonitorRequestTemplateRepository, NewContentModerationRepository, NewAffiliateRepository, diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go index a456c8c3701e..6c1b27a82141 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -657,6 +657,16 @@ func registerChannelMonitorRoutes(admin *gin.RouterGroup, h *handler.Handlers) { monitors.GET("/:id/history", h.Admin.ChannelMonitor.History) } + policies := admin.Group("/scheduling-policies") + { + policies.GET("", h.Admin.SchedulingPolicy.List) + policies.POST("", h.Admin.SchedulingPolicy.Create) + policies.GET("/actions", h.Admin.SchedulingPolicy.Actions) + policies.GET("/:id", h.Admin.SchedulingPolicy.Get) + policies.PUT("/:id", h.Admin.SchedulingPolicy.Update) + policies.DELETE("/:id", h.Admin.SchedulingPolicy.Delete) + } + templates := admin.Group("/channel-monitor-templates") { templates.GET("", h.Admin.ChannelMonitorTemplate.List) diff --git a/backend/internal/server/routes/user.go b/backend/internal/server/routes/user.go index 9f89687ad115..4571c2d88b15 100644 --- a/backend/internal/server/routes/user.go +++ b/backend/internal/server/routes/user.go @@ -78,6 +78,9 @@ func RegisterUserRoutes( channels.GET("/available", h.AvailableChannel.List) } + // 模型广场(登录版,按用户可访问分组过滤) + authenticated.GET("/model-plaza", h.AvailableChannel.ListModelPlaza) + // 使用记录 usage := authenticated.Group("/usage") { diff --git a/backend/internal/service/channel_monitor_service.go b/backend/internal/service/channel_monitor_service.go index 7b53bb20b099..51165811b89e 100644 --- a/backend/internal/service/channel_monitor_service.go +++ b/backend/internal/service/channel_monitor_service.go @@ -64,6 +64,14 @@ type ChannelMonitorService struct { // scheduler 由 wire 通过 SetScheduler 注入;CRUD 后调用对应钩子即时同步任务。 // 测试或未注入场景下保持 nil,所有钩子调用变为 no-op。 scheduler MonitorScheduler + // checkResultHook 由 wire 通过 SetCheckResultHook 注入(调度策略引擎); + // 每次 RunCheck 完成后同步回调。nil 时为 no-op。 + checkResultHook func(ctx context.Context, m *ChannelMonitor, results []*CheckResult) +} + +// SetCheckResultHook 注入检测结果回调(setter 注入避免 wire 依赖环)。 +func (s *ChannelMonitorService) SetCheckResultHook(hook func(ctx context.Context, m *ChannelMonitor, results []*CheckResult)) { + s.checkResultHook = hook } // NewChannelMonitorService 创建渠道监控服务实例。 @@ -267,6 +275,9 @@ func (s *ChannelMonitorService) RunCheck(ctx context.Context, id int64) ([]*Chec } results := s.runChecksConcurrent(ctx, m) s.persistCheckResults(ctx, m, results) + if s.checkResultHook != nil { + s.checkResultHook(ctx, m, results) + } return results, nil } diff --git a/backend/internal/service/scheduling_policy_service.go b/backend/internal/service/scheduling_policy_service.go new file mode 100644 index 000000000000..bf4fbf45bdc9 --- /dev/null +++ b/backend/internal/service/scheduling_policy_service.go @@ -0,0 +1,343 @@ +package service + +import ( + "context" + "fmt" + "log/slog" + "strings" + "sync" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +// ErrSchedulingPolicyNotFound 策略不存在。 +var ErrSchedulingPolicyNotFound = infraerrors.NotFound( + "SCHEDULING_POLICY_NOT_FOUND", "scheduling policy not found", +) + +// schedulingPauseMaxDuration pause_minutes=0(停用至恢复)时使用的兜底时长, +// 防止恢复链路异常导致账号被永久停用。 +const schedulingPauseMaxDuration = 30 * 24 * time.Hour + +// schedulingAccountRepo 策略引擎用到的账号仓储子集(AccountRepository 自然满足), +// 缩小接口面便于单测注入轻量 stub。 +type schedulingAccountRepo interface { + GetByID(ctx context.Context, id int64) (*Account, error) + SetTempUnschedulable(ctx context.Context, id int64, until time.Time, reason string) error + ClearTempUnschedulable(ctx context.Context, id int64) error + BulkUpdate(ctx context.Context, ids []int64, updates AccountBulkUpdate) (int64, error) +} + +// schedulingPolicyState 单个策略的运行时计数器(进程内)。 +type schedulingPolicyState struct { + consecutiveFailures int + consecutiveSuccesses int +} + +// SchedulingPolicyService 渠道调度策略服务: +// CRUD + 监控结果驱动的账号调度联动(自动临停/降级/恢复)+ 动作审计。 +type SchedulingPolicyService struct { + repo SchedulingPolicyRepository + accountRepo schedulingAccountRepo + + mu sync.Mutex + states map[int64]*schedulingPolicyState +} + +// NewSchedulingPolicyService 创建调度策略服务实例。 +func NewSchedulingPolicyService(repo SchedulingPolicyRepository, accountRepo schedulingAccountRepo) *SchedulingPolicyService { + return &SchedulingPolicyService{ + repo: repo, + accountRepo: accountRepo, + states: make(map[int64]*schedulingPolicyState), + } +} + +// ---------- CRUD ---------- + +func (s *SchedulingPolicyService) List(ctx context.Context, params SchedulingPolicyListParams) ([]*SchedulingPolicy, int64, error) { + if params.Page < 1 { + params.Page = 1 + } + if params.PageSize < 1 || params.PageSize > 100 { + params.PageSize = 20 + } + return s.repo.List(ctx, params) +} + +func (s *SchedulingPolicyService) Get(ctx context.Context, id int64) (*SchedulingPolicy, error) { + return s.repo.GetByID(ctx, id) +} + +func (s *SchedulingPolicyService) Create(ctx context.Context, p *SchedulingPolicy) error { + if err := validateSchedulingPolicy(p); err != nil { + return err + } + return s.repo.Create(ctx, p) +} + +func (s *SchedulingPolicyService) Update(ctx context.Context, p *SchedulingPolicy) error { + if err := validateSchedulingPolicy(p); err != nil { + return err + } + if err := s.repo.Update(ctx, p); err != nil { + return err + } + s.resetState(p.ID) + return nil +} + +func (s *SchedulingPolicyService) Delete(ctx context.Context, id int64) error { + if err := s.repo.Delete(ctx, id); err != nil { + return err + } + s.resetState(id) + return nil +} + +func (s *SchedulingPolicyService) ListActions(ctx context.Context, params SchedulingActionListParams) ([]*SchedulingActionRecord, int64, error) { + if params.Page < 1 { + params.Page = 1 + } + if params.PageSize < 1 || params.PageSize > 100 { + params.PageSize = 20 + } + return s.repo.ListActions(ctx, params) +} + +func validateSchedulingPolicy(p *SchedulingPolicy) error { + p.Name = strings.TrimSpace(p.Name) + if p.Name == "" { + return schedulingPolicyInvalid("name is required") + } + if p.MonitorID <= 0 { + return schedulingPolicyInvalid("monitor_id is required") + } + if len(p.AccountIDs) == 0 { + return schedulingPolicyInvalid("account_ids is required") + } + if p.ActionType != SchedulingActionPause && p.ActionType != SchedulingActionDeprioritize { + return schedulingPolicyInvalid(fmt.Sprintf("invalid action_type: %s", p.ActionType)) + } + if p.TriggerConsecutiveFailures < 1 || p.TriggerConsecutiveFailures > 100 { + return schedulingPolicyInvalid("trigger_consecutive_failures must be within [1, 100]") + } + if p.TriggerLatencyMs < 0 || p.TriggerLatencyMs > 600000 { + return schedulingPolicyInvalid("trigger_latency_ms must be within [0, 600000]") + } + if p.PauseMinutes < 0 || p.PauseMinutes > 10080 { + return schedulingPolicyInvalid("pause_minutes must be within [0, 10080]") + } + if p.PriorityDelta < 1 || p.PriorityDelta > 1000 { + return schedulingPolicyInvalid("priority_delta must be within [1, 1000]") + } + if p.RecoverConsecutiveSuccesses < 0 || p.RecoverConsecutiveSuccesses > 100 { + return schedulingPolicyInvalid("recover_consecutive_successes must be within [0, 100]") + } + if p.CooldownMinutes < 0 || p.CooldownMinutes > 1440 { + return schedulingPolicyInvalid("cooldown_minutes must be within [0, 1440]") + } + return nil +} + +func schedulingPolicyInvalid(msg string) error { + return infraerrors.BadRequest("SCHEDULING_POLICY_INVALID", msg) +} + +// ---------- 引擎:监控结果驱动 ---------- + +// OnCheckResults 渠道监控检查完成后的回调入口。 +// 由 ChannelMonitorService.RunCheck 在写入历史后调用;内部自行吞掉错误(只记日志), +// 保证监控主链路不受策略引擎故障影响。 +func (s *SchedulingPolicyService) OnCheckResults(ctx context.Context, monitor *ChannelMonitor, results []*CheckResult) { + if s == nil || monitor == nil || len(results) == 0 { + return + } + policies, err := s.repo.ListEnabledByMonitorID(ctx, monitor.ID) + if err != nil { + slog.Error("scheduling policy: list by monitor failed", "monitor_id", monitor.ID, "error", err) + return + } + for _, p := range policies { + s.evaluate(ctx, p, monitor, results) + } +} + +// evaluate 用一次检查结果推进单个策略的状态机。 +func (s *SchedulingPolicyService) evaluate(ctx context.Context, p *SchedulingPolicy, monitor *ChannelMonitor, results []*CheckResult) { + failed, reason := checkFailedForPolicy(p, monitor, results) + + s.mu.Lock() + st, ok := s.states[p.ID] + if !ok { + st = &schedulingPolicyState{} + s.states[p.ID] = st + } + if failed { + st.consecutiveFailures++ + st.consecutiveSuccesses = 0 + } else { + st.consecutiveSuccesses++ + st.consecutiveFailures = 0 + } + failures, successes := st.consecutiveFailures, st.consecutiveSuccesses + s.mu.Unlock() + + if failed && failures >= p.TriggerConsecutiveFailures { + s.trigger(ctx, p, reason) + return + } + if !failed && p.RecoverConsecutiveSuccesses > 0 && successes >= p.RecoverConsecutiveSuccesses { + s.recover(ctx, p) + } +} + +// checkFailedForPolicy 判定一次检查是否计为失败。 +// 取主模型结果(缺失时取第一条);status 为 failed/error 或延迟超过阈值均计为失败。 +func checkFailedForPolicy(p *SchedulingPolicy, monitor *ChannelMonitor, results []*CheckResult) (bool, string) { + r := results[0] + for _, cand := range results { + if cand.Model == monitor.PrimaryModel { + r = cand + break + } + } + if r.Status == "failed" || r.Status == "error" { + msg := r.Message + if len(msg) > 200 { + msg = msg[:200] + } + return true, fmt.Sprintf("monitor %q model %s status=%s %s", monitor.Name, r.Model, r.Status, msg) + } + if p.TriggerLatencyMs > 0 && r.LatencyMs != nil && *r.LatencyMs > p.TriggerLatencyMs { + return true, fmt.Sprintf("monitor %q model %s latency %dms > %dms", monitor.Name, r.Model, *r.LatencyMs, p.TriggerLatencyMs) + } + return false, "" +} + +// trigger 对策略目标账号执行动作(跳过已有未恢复动作的账号),并写审计。 +func (s *SchedulingPolicyService) trigger(ctx context.Context, p *SchedulingPolicy, reason string) { + if s.accountRepo == nil { + return + } + last, err := s.repo.LatestTriggerAt(ctx, p.ID) + if err != nil { + slog.Error("scheduling policy: query latest trigger failed", "policy_id", p.ID, "error", err) + return + } + if last != nil && p.CooldownMinutes > 0 && time.Since(*last) < time.Duration(p.CooldownMinutes)*time.Minute { + return + } + + active, err := s.repo.ListUnrestoredActions(ctx, p.ID) + if err != nil { + slog.Error("scheduling policy: list unrestored actions failed", "policy_id", p.ID, "error", err) + return + } + activeAccounts := make(map[int64]struct{}, len(active)) + for _, a := range active { + activeAccounts[a.AccountID] = struct{}{} + } + + for _, accountID := range p.AccountIDs { + if _, exists := activeAccounts[accountID]; exists { + continue + } + account, err := s.accountRepo.GetByID(ctx, accountID) + if err != nil { + slog.Warn("scheduling policy: account not found, skip", "policy_id", p.ID, "account_id", accountID) + continue + } + record := &SchedulingActionRecord{ + PolicyID: p.ID, + AccountID: accountID, + MonitorID: p.MonitorID, + Action: p.ActionType, + Reason: reason, + } + switch p.ActionType { + case SchedulingActionPause: + until := time.Now().Add(schedulingPauseMaxDuration) + if p.PauseMinutes > 0 { + until = time.Now().Add(time.Duration(p.PauseMinutes) * time.Minute) + } + if err := s.accountRepo.SetTempUnschedulable(ctx, accountID, until, "scheduling policy: "+p.Name); err != nil { + slog.Error("scheduling policy: pause account failed", "policy_id", p.ID, "account_id", accountID, "error", err) + continue + } + case SchedulingActionDeprioritize: + record.OriginalPriority = account.Priority + newPriority := account.Priority + p.PriorityDelta + if _, err := s.accountRepo.BulkUpdate(ctx, []int64{accountID}, AccountBulkUpdate{Priority: &newPriority}); err != nil { + slog.Error("scheduling policy: deprioritize account failed", "policy_id", p.ID, "account_id", accountID, "error", err) + continue + } + default: + continue + } + if err := s.repo.InsertAction(ctx, record); err != nil { + slog.Error("scheduling policy: insert action failed", "policy_id", p.ID, "account_id", accountID, "error", err) + } + slog.Info("scheduling policy triggered", + "policy_id", p.ID, "policy", p.Name, "account_id", accountID, "action", p.ActionType, "reason", reason) + } +} + +// recover 恢复策略下所有未恢复的动作并写审计。 +func (s *SchedulingPolicyService) recover(ctx context.Context, p *SchedulingPolicy) { + if s.accountRepo == nil { + return + } + active, err := s.repo.ListUnrestoredActions(ctx, p.ID) + if err != nil { + slog.Error("scheduling policy: list unrestored actions failed", "policy_id", p.ID, "error", err) + return + } + if len(active) == 0 { + return + } + restoredIDs := make([]int64, 0, len(active)) + for _, a := range active { + switch a.Action { + case SchedulingActionPause: + if err := s.accountRepo.ClearTempUnschedulable(ctx, a.AccountID); err != nil { + slog.Error("scheduling policy: clear pause failed", "policy_id", p.ID, "account_id", a.AccountID, "error", err) + continue + } + case SchedulingActionDeprioritize: + original := a.OriginalPriority + if _, err := s.accountRepo.BulkUpdate(ctx, []int64{a.AccountID}, AccountBulkUpdate{Priority: &original}); err != nil { + slog.Error("scheduling policy: restore priority failed", "policy_id", p.ID, "account_id", a.AccountID, "error", err) + continue + } + default: + continue + } + restoredIDs = append(restoredIDs, a.ID) + recoverRecord := &SchedulingActionRecord{ + PolicyID: p.ID, + AccountID: a.AccountID, + MonitorID: p.MonitorID, + Action: SchedulingActionRecover, + Reason: fmt.Sprintf("recovered after %d consecutive successes", p.RecoverConsecutiveSuccesses), + Restored: true, + } + if err := s.repo.InsertAction(ctx, recoverRecord); err != nil { + slog.Error("scheduling policy: insert recover action failed", "policy_id", p.ID, "account_id", a.AccountID, "error", err) + } + slog.Info("scheduling policy recovered", "policy_id", p.ID, "policy", p.Name, "account_id", a.AccountID) + } + if len(restoredIDs) > 0 { + if err := s.repo.MarkActionsRestored(ctx, restoredIDs); err != nil { + slog.Error("scheduling policy: mark restored failed", "policy_id", p.ID, "error", err) + } + } +} + +// resetState 清空策略的进程内计数器(配置变更/删除后重新累计)。 +func (s *SchedulingPolicyService) resetState(policyID int64) { + s.mu.Lock() + delete(s.states, policyID) + s.mu.Unlock() +} diff --git a/backend/internal/service/scheduling_policy_service_test.go b/backend/internal/service/scheduling_policy_service_test.go new file mode 100644 index 000000000000..1a56fe79e883 --- /dev/null +++ b/backend/internal/service/scheduling_policy_service_test.go @@ -0,0 +1,289 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + "time" +) + +// ---------- stubs ---------- + +type stubSchedulingPolicyRepo struct { + policies []*SchedulingPolicy + actions []*SchedulingActionRecord + nextActive int64 +} + +func (r *stubSchedulingPolicyRepo) Create(_ context.Context, p *SchedulingPolicy) error { + r.policies = append(r.policies, p) + return nil +} +func (r *stubSchedulingPolicyRepo) GetByID(_ context.Context, id int64) (*SchedulingPolicy, error) { + for _, p := range r.policies { + if p.ID == id { + return p, nil + } + } + return nil, ErrSchedulingPolicyNotFound +} +func (r *stubSchedulingPolicyRepo) Update(_ context.Context, _ *SchedulingPolicy) error { return nil } +func (r *stubSchedulingPolicyRepo) Delete(_ context.Context, _ int64) error { return nil } +func (r *stubSchedulingPolicyRepo) List(_ context.Context, _ SchedulingPolicyListParams) ([]*SchedulingPolicy, int64, error) { + return r.policies, int64(len(r.policies)), nil +} +func (r *stubSchedulingPolicyRepo) ListEnabledByMonitorID(_ context.Context, monitorID int64) ([]*SchedulingPolicy, error) { + var out []*SchedulingPolicy + for _, p := range r.policies { + if p.Enabled && p.MonitorID == monitorID { + out = append(out, p) + } + } + return out, nil +} +func (r *stubSchedulingPolicyRepo) InsertAction(_ context.Context, a *SchedulingActionRecord) error { + r.nextActive++ + a.ID = r.nextActive + a.CreatedAt = time.Now() + r.actions = append(r.actions, a) + return nil +} +func (r *stubSchedulingPolicyRepo) ListActions(_ context.Context, _ SchedulingActionListParams) ([]*SchedulingActionRecord, int64, error) { + return r.actions, int64(len(r.actions)), nil +} +func (r *stubSchedulingPolicyRepo) ListUnrestoredActions(_ context.Context, policyID int64) ([]*SchedulingActionRecord, error) { + var out []*SchedulingActionRecord + for _, a := range r.actions { + if a.PolicyID == policyID && !a.Restored && a.Action != SchedulingActionRecover { + out = append(out, a) + } + } + return out, nil +} +func (r *stubSchedulingPolicyRepo) MarkActionsRestored(_ context.Context, ids []int64) error { + idSet := make(map[int64]struct{}, len(ids)) + for _, id := range ids { + idSet[id] = struct{}{} + } + for _, a := range r.actions { + if _, ok := idSet[a.ID]; ok { + a.Restored = true + } + } + return nil +} +func (r *stubSchedulingPolicyRepo) LatestTriggerAt(_ context.Context, policyID int64) (*time.Time, error) { + var latest *time.Time + for _, a := range r.actions { + if a.PolicyID == policyID && a.Action != SchedulingActionRecover { + t := a.CreatedAt + latest = &t + } + } + return latest, nil +} + +type stubSchedulingAccountRepo struct { + accounts map[int64]*Account + pausedUntil map[int64]time.Time + pauseCleared map[int64]bool + priorityWrites map[int64]int +} + +func newStubSchedulingAccountRepo(accounts ...*Account) *stubSchedulingAccountRepo { + m := make(map[int64]*Account) + for _, a := range accounts { + m[a.ID] = a + } + return &stubSchedulingAccountRepo{ + accounts: m, + pausedUntil: make(map[int64]time.Time), + pauseCleared: make(map[int64]bool), + priorityWrites: make(map[int64]int), + } +} + +func (r *stubSchedulingAccountRepo) GetByID(_ context.Context, id int64) (*Account, error) { + a, ok := r.accounts[id] + if !ok { + return nil, ErrAccountNotFound + } + return a, nil +} +func (r *stubSchedulingAccountRepo) SetTempUnschedulable(_ context.Context, id int64, until time.Time, _ string) error { + r.pausedUntil[id] = until + return nil +} +func (r *stubSchedulingAccountRepo) ClearTempUnschedulable(_ context.Context, id int64) error { + r.pauseCleared[id] = true + return nil +} +func (r *stubSchedulingAccountRepo) BulkUpdate(_ context.Context, ids []int64, updates AccountBulkUpdate) (int64, error) { + for _, id := range ids { + if updates.Priority != nil { + r.priorityWrites[id] = *updates.Priority + if a, ok := r.accounts[id]; ok { + a.Priority = *updates.Priority + } + } + } + return int64(len(ids)), nil +} + +// ---------- helpers ---------- + +func testPolicy() *SchedulingPolicy { + return &SchedulingPolicy{ + ID: 1, + Name: "policy", + Enabled: true, + MonitorID: 7, + AccountIDs: []int64{100}, + TriggerConsecutiveFailures: 2, + ActionType: SchedulingActionPause, + PauseMinutes: 30, + PriorityDelta: 10, + RecoverConsecutiveSuccesses: 2, + CooldownMinutes: 0, + } +} + +func testMonitor() *ChannelMonitor { + return &ChannelMonitor{ID: 7, Name: "mon", PrimaryModel: "gpt-4o"} +} + +func failedResults() []*CheckResult { + return []*CheckResult{{Model: "gpt-4o", Status: "failed", Message: "boom", CheckedAt: time.Now()}} +} + +func okResults() []*CheckResult { + return []*CheckResult{{Model: "gpt-4o", Status: "operational", CheckedAt: time.Now()}} +} + +// ---------- tests ---------- + +func TestSchedulingPolicyPauseAfterConsecutiveFailures(t *testing.T) { + repo := &stubSchedulingPolicyRepo{policies: []*SchedulingPolicy{testPolicy()}} + accounts := newStubSchedulingAccountRepo(&Account{ID: 100, Priority: 50}) + svc := NewSchedulingPolicyService(repo, accounts) + ctx := context.Background() + + svc.OnCheckResults(ctx, testMonitor(), failedResults()) + if len(accounts.pausedUntil) != 0 { + t.Fatal("should not pause after single failure") + } + svc.OnCheckResults(ctx, testMonitor(), failedResults()) + if _, ok := accounts.pausedUntil[100]; !ok { + t.Fatal("expected account 100 paused after 2 consecutive failures") + } + if len(repo.actions) != 1 || repo.actions[0].Action != SchedulingActionPause { + t.Fatalf("expected 1 pause action, got %+v", repo.actions) + } +} + +func TestSchedulingPolicyRecoverAfterConsecutiveSuccesses(t *testing.T) { + repo := &stubSchedulingPolicyRepo{policies: []*SchedulingPolicy{testPolicy()}} + accounts := newStubSchedulingAccountRepo(&Account{ID: 100, Priority: 50}) + svc := NewSchedulingPolicyService(repo, accounts) + ctx := context.Background() + + svc.OnCheckResults(ctx, testMonitor(), failedResults()) + svc.OnCheckResults(ctx, testMonitor(), failedResults()) + svc.OnCheckResults(ctx, testMonitor(), okResults()) + if accounts.pauseCleared[100] { + t.Fatal("should not recover after single success") + } + svc.OnCheckResults(ctx, testMonitor(), okResults()) + if !accounts.pauseCleared[100] { + t.Fatal("expected pause cleared after 2 consecutive successes") + } + var recovered bool + for _, a := range repo.actions { + if a.Action == SchedulingActionRecover { + recovered = true + } + if a.Action == SchedulingActionPause && !a.Restored { + t.Fatal("pause action should be marked restored") + } + } + if !recovered { + t.Fatal("expected recover audit record") + } +} + +func TestSchedulingPolicyDeprioritizeAndRestore(t *testing.T) { + p := testPolicy() + p.ActionType = SchedulingActionDeprioritize + p.PriorityDelta = 25 + repo := &stubSchedulingPolicyRepo{policies: []*SchedulingPolicy{p}} + accounts := newStubSchedulingAccountRepo(&Account{ID: 100, Priority: 50}) + svc := NewSchedulingPolicyService(repo, accounts) + ctx := context.Background() + + svc.OnCheckResults(ctx, testMonitor(), failedResults()) + svc.OnCheckResults(ctx, testMonitor(), failedResults()) + if got := accounts.priorityWrites[100]; got != 75 { + t.Fatalf("expected priority 75, got %d", got) + } + svc.OnCheckResults(ctx, testMonitor(), okResults()) + svc.OnCheckResults(ctx, testMonitor(), okResults()) + if got := accounts.priorityWrites[100]; got != 50 { + t.Fatalf("expected priority restored to 50, got %d", got) + } +} + +func TestSchedulingPolicyLatencyTrigger(t *testing.T) { + p := testPolicy() + p.TriggerConsecutiveFailures = 1 + p.TriggerLatencyMs = 1000 + repo := &stubSchedulingPolicyRepo{policies: []*SchedulingPolicy{p}} + accounts := newStubSchedulingAccountRepo(&Account{ID: 100, Priority: 50}) + svc := NewSchedulingPolicyService(repo, accounts) + ctx := context.Background() + + slow := 1500 + svc.OnCheckResults(ctx, testMonitor(), []*CheckResult{ + {Model: "gpt-4o", Status: "operational", LatencyMs: &slow, CheckedAt: time.Now()}, + }) + if _, ok := accounts.pausedUntil[100]; !ok { + t.Fatal("expected latency breach to trigger pause") + } +} + +func TestSchedulingPolicyNoDuplicateTrigger(t *testing.T) { + repo := &stubSchedulingPolicyRepo{policies: []*SchedulingPolicy{testPolicy()}} + accounts := newStubSchedulingAccountRepo(&Account{ID: 100, Priority: 50}) + svc := NewSchedulingPolicyService(repo, accounts) + ctx := context.Background() + + for i := 0; i < 5; i++ { + svc.OnCheckResults(ctx, testMonitor(), failedResults()) + } + pauses := 0 + for _, a := range repo.actions { + if a.Action == SchedulingActionPause { + pauses++ + } + } + if pauses != 1 { + t.Fatalf("expected exactly 1 pause action, got %d", pauses) + } +} + +func TestValidateSchedulingPolicy(t *testing.T) { + p := testPolicy() + if err := validateSchedulingPolicy(p); err != nil { + t.Fatalf("valid policy rejected: %v", err) + } + bad := testPolicy() + bad.ActionType = "nuke" + if err := validateSchedulingPolicy(bad); err == nil { + t.Fatal("expected invalid action_type error") + } + bad2 := testPolicy() + bad2.AccountIDs = nil + if err := validateSchedulingPolicy(bad2); err == nil { + t.Fatal("expected account_ids required error") + } +} diff --git a/backend/internal/service/scheduling_policy_types.go b/backend/internal/service/scheduling_policy_types.go new file mode 100644 index 000000000000..2fc0d025b4b7 --- /dev/null +++ b/backend/internal/service/scheduling_policy_types.go @@ -0,0 +1,79 @@ +package service + +import ( + "context" + "time" +) + +// 调度策略动作类型。 +const ( + SchedulingActionPause = "pause" + SchedulingActionDeprioritize = "deprioritize" + SchedulingActionRecover = "recover" +) + +// SchedulingPolicy 渠道调度策略领域模型。 +// 条件源为一个渠道监控(channel_monitor),动作目标为若干账号。 +type SchedulingPolicy struct { + ID int64 + Name string + Enabled bool + MonitorID int64 + AccountIDs []int64 + TriggerConsecutiveFailures int + TriggerLatencyMs int + ActionType string // pause / deprioritize + PauseMinutes int // 0 = 停用至恢复条件满足 + PriorityDelta int + RecoverConsecutiveSuccesses int // 0 = 不自动恢复 + CooldownMinutes int + CreatedAt time.Time + UpdatedAt time.Time +} + +// SchedulingActionRecord 策略动作审计记录。 +type SchedulingActionRecord struct { + ID int64 + PolicyID int64 + AccountID int64 + MonitorID int64 + Action string + Reason string + OriginalPriority int + Restored bool + CreatedAt time.Time +} + +// SchedulingPolicyListParams 策略列表过滤参数。 +type SchedulingPolicyListParams struct { + Page int + PageSize int + Enabled *bool + Search string +} + +// SchedulingActionListParams 动作历史查询参数。 +type SchedulingActionListParams struct { + Page int + PageSize int + PolicyID int64 // 0 = 全部 + AccountID int64 // 0 = 全部 +} + +// SchedulingPolicyRepository 调度策略数据访问接口。 +type SchedulingPolicyRepository interface { + Create(ctx context.Context, p *SchedulingPolicy) error + GetByID(ctx context.Context, id int64) (*SchedulingPolicy, error) + Update(ctx context.Context, p *SchedulingPolicy) error + Delete(ctx context.Context, id int64) error + List(ctx context.Context, params SchedulingPolicyListParams) ([]*SchedulingPolicy, int64, error) + ListEnabledByMonitorID(ctx context.Context, monitorID int64) ([]*SchedulingPolicy, error) + + InsertAction(ctx context.Context, a *SchedulingActionRecord) error + ListActions(ctx context.Context, params SchedulingActionListParams) ([]*SchedulingActionRecord, int64, error) + // ListUnrestoredActions 返回策略下未恢复的触发动作(pause/deprioritize)。 + ListUnrestoredActions(ctx context.Context, policyID int64) ([]*SchedulingActionRecord, error) + MarkActionsRestored(ctx context.Context, ids []int64) error + // LatestTriggerAt 返回策略最近一次触发动作(非 recover)的时间;无记录返回 nil。 + LatestTriggerAt(ctx context.Context, policyID int64) (*time.Time, error) +} diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index 7258ff05a324..7a6ed2cdf60a 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -659,9 +659,22 @@ var ProviderSet = wire.NewSet( ProvideChannelMonitorService, ProvideChannelMonitorRunner, NewChannelMonitorRequestTemplateService, + ProvideSchedulingPolicyService, ProvideUserPlatformQuotaUsageFlusher, ) +// ProvideSchedulingPolicyService 创建调度策略服务,并把策略引擎挂到渠道监控的检测结果回调上, +// 使每次监控检测完成后自动评估策略并执行账号调度动作。 +func ProvideSchedulingPolicyService( + repo SchedulingPolicyRepository, + accountRepo AccountRepository, + monitorService *ChannelMonitorService, +) *SchedulingPolicyService { + svc := NewSchedulingPolicyService(repo, accountRepo) + monitorService.SetCheckResultHook(svc.OnCheckResults) + return svc +} + // ProvideUserPlatformQuotaUsageFlusher 创建并启动 UserPlatformQuotaUsageFlusher。 func ProvideUserPlatformQuotaUsageFlusher(cfg *config.Config, cache BillingCache, quotaRepo UserPlatformQuotaRepository, tw *TimingWheelService) *UserPlatformQuotaUsageFlusher { svc := NewUserPlatformQuotaUsageFlusher(cfg, cache, quotaRepo, tw) diff --git a/backend/migrations/173_add_scheduling_policies.sql b/backend/migrations/173_add_scheduling_policies.sql new file mode 100644 index 000000000000..8bbd5189d59d --- /dev/null +++ b/backend/migrations/173_add_scheduling_policies.sql @@ -0,0 +1,37 @@ +-- 173_add_scheduling_policies.sql +-- 渠道调度策略:监控结果 → 账号调度动作联动(自动临停/降级/恢复)+ 动作审计。 + +CREATE TABLE IF NOT EXISTS scheduling_policies ( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(100) NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + monitor_id BIGINT NOT NULL, + account_ids JSONB NOT NULL DEFAULT '[]', + trigger_consecutive_failures INTEGER NOT NULL DEFAULT 3, + trigger_latency_ms INTEGER NOT NULL DEFAULT 0, + action_type VARCHAR(32) NOT NULL DEFAULT 'pause', + pause_minutes INTEGER NOT NULL DEFAULT 0, + priority_delta INTEGER NOT NULL DEFAULT 10, + recover_consecutive_successes INTEGER NOT NULL DEFAULT 2, + cooldown_minutes INTEGER NOT NULL DEFAULT 10, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS schedulingpolicy_monitor_id ON scheduling_policies (monitor_id); +CREATE INDEX IF NOT EXISTS schedulingpolicy_enabled ON scheduling_policies (enabled); + +CREATE TABLE IF NOT EXISTS scheduling_actions ( + id BIGSERIAL PRIMARY KEY, + policy_id BIGINT NOT NULL, + account_id BIGINT NOT NULL, + monitor_id BIGINT NOT NULL, + action VARCHAR(32) NOT NULL, + reason VARCHAR(500) NOT NULL DEFAULT '', + original_priority INTEGER NOT NULL DEFAULT 0, + restored BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX IF NOT EXISTS schedulingaction_policy_id_created_at ON scheduling_actions (policy_id, created_at); +CREATE INDEX IF NOT EXISTS schedulingaction_account_id_restored ON scheduling_actions (account_id, restored); diff --git a/frontend/src/api/admin/index.ts b/frontend/src/api/admin/index.ts index 1698a92c432e..55ce3112fdaf 100644 --- a/frontend/src/api/admin/index.ts +++ b/frontend/src/api/admin/index.ts @@ -29,6 +29,7 @@ import tlsFingerprintProfileAPI from './tlsFingerprintProfile' import channelsAPI from './channels' import channelMonitorAPI from './channelMonitor' import channelMonitorTemplateAPI from './channelMonitorTemplate' +import schedulingPoliciesAPI from './schedulingPolicies' import adminPaymentAPI from './payment' import affiliatesAPI from './affiliates' import riskControlAPI from './riskControl' @@ -64,6 +65,7 @@ export const adminAPI = { channels: channelsAPI, channelMonitor: channelMonitorAPI, channelMonitorTemplate: channelMonitorTemplateAPI, + schedulingPolicies: schedulingPoliciesAPI, payment: adminPaymentAPI, affiliates: affiliatesAPI, riskControl: riskControlAPI, @@ -97,6 +99,7 @@ export { channelsAPI, channelMonitorAPI, channelMonitorTemplateAPI, + schedulingPoliciesAPI, adminPaymentAPI, affiliatesAPI, riskControlAPI, diff --git a/frontend/src/api/admin/schedulingPolicies.ts b/frontend/src/api/admin/schedulingPolicies.ts new file mode 100644 index 000000000000..4e5533231c4e --- /dev/null +++ b/frontend/src/api/admin/schedulingPolicies.ts @@ -0,0 +1,131 @@ +/** + * Admin Scheduling Policy API endpoints + * Monitor-driven channel/account scheduling automation (pause / deprioritize / recover) + */ + +import { apiClient } from '../client' + +export type SchedulingActionType = 'pause' | 'deprioritize' +export type SchedulingActionKind = 'pause' | 'deprioritize' | 'recover' + +export interface SchedulingPolicy { + id: number + name: string + enabled: boolean + monitor_id: number + account_ids: number[] + trigger_consecutive_failures: number + trigger_latency_ms: number + action_type: SchedulingActionType + pause_minutes: number + priority_delta: number + recover_consecutive_successes: number + cooldown_minutes: number + created_at: string + updated_at: string +} + +export interface SchedulingPolicyParams { + name: string + enabled?: boolean + monitor_id: number + account_ids: number[] + trigger_consecutive_failures: number + trigger_latency_ms?: number + action_type: SchedulingActionType + pause_minutes?: number + priority_delta?: number + recover_consecutive_successes?: number + cooldown_minutes?: number +} + +export interface SchedulingPolicyListParams { + page?: number + page_size?: number + enabled?: boolean + search?: string +} + +export interface SchedulingPolicyListResponse { + items: SchedulingPolicy[] + total: number + page: number + page_size: number + pages: number +} + +export interface SchedulingAction { + id: number + policy_id: number + account_id: number + monitor_id: number + action: SchedulingActionKind + reason: string + original_priority: number + restored: boolean + created_at: string +} + +export interface SchedulingActionListParams { + page?: number + page_size?: number + policy_id?: number + account_id?: number +} + +export interface SchedulingActionListResponse { + items: SchedulingAction[] + total: number + page: number + page_size: number + pages: number +} + +export async function list( + params: SchedulingPolicyListParams = {} +): Promise { + const { data } = await apiClient.get('/admin/scheduling-policies', { + params, + }) + return data +} + +export async function get(id: number): Promise { + const { data } = await apiClient.get(`/admin/scheduling-policies/${id}`) + return data +} + +export async function create(params: SchedulingPolicyParams): Promise { + const { data } = await apiClient.post('/admin/scheduling-policies', params) + return data +} + +export async function update(id: number, params: SchedulingPolicyParams): Promise { + const { data } = await apiClient.put(`/admin/scheduling-policies/${id}`, params) + return data +} + +export async function remove(id: number): Promise { + await apiClient.delete(`/admin/scheduling-policies/${id}`) +} + +export async function listActions( + params: SchedulingActionListParams = {} +): Promise { + const { data } = await apiClient.get( + '/admin/scheduling-policies/actions', + { params } + ) + return data +} + +export const schedulingPoliciesAPI = { + list, + get, + create, + update, + remove, + listActions, +} + +export default schedulingPoliciesAPI diff --git a/frontend/src/api/modelPlaza.ts b/frontend/src/api/modelPlaza.ts new file mode 100644 index 000000000000..9c146cdf2ae1 --- /dev/null +++ b/frontend/src/api/modelPlaza.ts @@ -0,0 +1,23 @@ +/** + * 模型广场 API:以模型为中心聚合定价与分组倍率,按用户可访问分组过滤。 + */ + +import { apiClient } from './client' +import type { UserAvailableGroup, UserSupportedModelPricing } from './channels' + +export interface ModelPlazaEntry { + name: string + platform: string + pricing: UserSupportedModelPricing | null + groups: UserAvailableGroup[] +} + +/** 模型广场(按用户可访问分组过滤,含专属分组)。 */ +export async function getModelPlaza(): Promise { + const { data } = await apiClient.get('/model-plaza') + return data || [] +} + +export const modelPlazaAPI = { getModelPlaza } + +export default modelPlazaAPI diff --git a/frontend/src/components/layout/AppSidebar.vue b/frontend/src/components/layout/AppSidebar.vue index ad78c2d298db..75235984d600 100644 --- a/frontend/src/components/layout/AppSidebar.vue +++ b/frontend/src/components/layout/AppSidebar.vue @@ -627,6 +627,21 @@ const SignalIcon = { ) } +const BoltIcon = { + render: () => + h( + 'svg', + { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, + [ + h('path', { + 'stroke-linecap': 'round', + 'stroke-linejoin': 'round', + d: 'M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z' + }) + ] + ) +} + const ShieldIcon = { render: () => h( @@ -704,6 +719,7 @@ function buildSelfNavItems(withDashboard: boolean): NavItem[] { { path: '/batch-image', label: t('nav.batchImage'), icon: BatchImageIcon, hideInSimpleMode: true, featureFlag: flagBatchImageAccess }, { path: '/usage', label: t('nav.usage'), icon: ChartIcon, hideInSimpleMode: true }, { path: '/available-channels', label: t('nav.availableChannels'), icon: ChannelIcon, hideInSimpleMode: true, featureFlag: flagAvailableChannels }, + { path: '/models', label: t('nav.modelPlaza'), icon: ChannelIcon, hideInSimpleMode: true, featureFlag: flagAvailableChannels }, { path: '/monitor', label: t('nav.channelStatus'), icon: SignalIcon, featureFlag: flagChannelMonitor }, { path: '/subscriptions', label: t('nav.mySubscriptions'), icon: CreditCardIcon, hideInSimpleMode: true }, { path: '/purchase', label: t('nav.buySubscription'), icon: RechargeSubscriptionIcon, hideInSimpleMode: true, featureFlag: flagPayment }, @@ -765,6 +781,7 @@ const adminNavItems = computed((): NavItem[] => { children: [ { path: '/admin/channels/pricing', label: t('nav.channelPricing'), icon: PriceTagIcon }, { path: '/admin/channels/monitor', label: t('nav.channelMonitor'), icon: SignalIcon, featureFlag: flagChannelMonitor }, + { path: '/admin/scheduling-policies', label: t('nav.schedulingPolicies'), icon: BoltIcon, featureFlag: flagChannelMonitor }, ], }, { path: '/admin/subscriptions', label: t('nav.subscriptions'), icon: CreditCardIcon, hideInSimpleMode: true }, diff --git a/frontend/src/i18n/locales/en/admin/channels.ts b/frontend/src/i18n/locales/en/admin/channels.ts index 07a24d0fd5d4..93d67cf1664d 100644 --- a/frontend/src/i18n/locales/en/admin/channels.ts +++ b/frontend/src/i18n/locales/en/admin/channels.ts @@ -462,6 +462,78 @@ export default { }, }, + // Scheduling Policies + schedulingPolicies: { + title: 'Scheduling Policies', + description: 'Automatically pause / deprioritize / recover accounts based on channel monitor results', + tabPolicies: 'Policies', + tabActions: 'Action History', + searchPlaceholder: 'Search policy name...', + createButton: 'New Policy', + createTitle: 'New Scheduling Policy', + editTitle: 'Edit Scheduling Policy', + allPolicies: 'All Policies', + accountsCount: '{count} accounts', + failuresSummary: '{count} consecutive failures', + latencySummary: 'latency > {ms}ms', + pauseSummary: 'Pause {minutes} min', + pauseUntilRecoverySummary: 'Pause until recovery', + deprioritizeSummary: 'Priority +{delta}', + restored: 'Restored', + active: 'Active', + noPoliciesYet: 'No scheduling policies yet', + createFirstPolicy: 'Create your first policy to let monitor results drive account scheduling', + noActionsYet: 'No scheduling actions yet', + noActionsHint: 'Trigger and recovery events will be audited here', + loadError: 'Failed to load', + createSuccess: 'Policy created', + updateSuccess: 'Policy updated', + deleteSuccess: 'Policy deleted', + deleteConfirm: 'Delete policy "{name}"? This cannot be undone.', + monitorRequired: 'Please select a monitor', + accountsRequired: 'Please select at least one account', + actionKinds: { + pause: 'Pause', + deprioritize: 'Deprioritize', + recover: 'Recover' + }, + columns: { + name: 'Name', + monitor: 'Monitor', + accounts: 'Target Accounts', + condition: 'Trigger Condition', + action: 'Action', + enabled: 'Enabled', + actions: 'Actions', + policy: 'Policy', + account: 'Account', + reason: 'Reason', + status: 'Status', + time: 'Time' + }, + form: { + name: 'Policy Name', + namePlaceholder: 'Enter policy name', + monitor: 'Monitor', + monitorPlaceholder: 'Select a channel monitor', + accounts: 'Target Accounts', + noAccounts: 'No accounts available', + consecutiveFailures: 'Consecutive Failures', + latencyThreshold: 'Latency Threshold (ms)', + latencyThresholdHint: '0 = do not trigger on latency', + actionType: 'Action', + pauseMinutes: 'Pause Duration (min)', + pauseMinutesHint: '0 = pause until recovery condition is met (30-day safety cap)', + priorityDelta: 'Priority Delta', + priorityDeltaHint: 'Higher value = lower priority; original value restored on recovery', + recoverSuccesses: 'Consecutive Successes to Recover', + recoverSuccessesHint: '0 = no auto recovery, manual handling required', + cooldownMinutes: 'Cooldown (min)', + cooldownMinutesHint: 'Minimum interval between triggers to prevent flapping', + enabled: 'Enable policy' + } + }, + // Channel Monitor channelMonitor: { title: 'Channel Monitor', diff --git a/frontend/src/i18n/locales/en/common.ts b/frontend/src/i18n/locales/en/common.ts index ac0b8dfcae05..6330e49b767b 100644 --- a/frontend/src/i18n/locales/en/common.ts +++ b/frontend/src/i18n/locales/en/common.ts @@ -163,6 +163,7 @@ export default { groups: 'Groups', channels: 'Channels', availableChannels: 'Available Channels', + modelPlaza: 'Model Plaza', subscriptions: 'Subscriptions', accounts: 'Accounts', proxies: 'Proxies', @@ -188,6 +189,7 @@ export default { channelManagement: 'Channels', channelPricing: 'Channel Pricing', channelMonitor: 'Channel Monitor', + schedulingPolicies: 'Scheduling Policies', channelStatus: 'Channel Status', riskControl: 'Risk Control', }, diff --git a/frontend/src/i18n/locales/en/index.ts b/frontend/src/i18n/locales/en/index.ts index 377c67aec7c4..c408db418359 100644 --- a/frontend/src/i18n/locales/en/index.ts +++ b/frontend/src/i18n/locales/en/index.ts @@ -3,6 +3,7 @@ import common from './common' import dashboard from './dashboard' import admin from './admin' import misc from './misc' +import modelPlaza from './modelPlaza' export default { ...landing, @@ -10,4 +11,5 @@ export default { ...dashboard, admin, ...misc, + ...modelPlaza, } diff --git a/frontend/src/i18n/locales/en/modelPlaza.ts b/frontend/src/i18n/locales/en/modelPlaza.ts new file mode 100644 index 000000000000..4c5aad0ddc98 --- /dev/null +++ b/frontend/src/i18n/locales/en/modelPlaza.ts @@ -0,0 +1,39 @@ +export default { + modelPlaza: { + title: 'Model Plaza', + description: 'Browse models available to your groups with official pricing', + bannerDescription: 'Explore model pricing and group information', + searchPlaceholder: 'Search model name or provider...', + allGroups: 'All Groups', + provider: 'Provider', + allProviders: 'All Providers', + type: 'Type', + allTypes: 'All Types', + typeChat: 'Chat', + typePerRequest: 'Per Request', + sortName: 'Model Name', + sortInputAsc: 'Input Price ↑', + sortInputDesc: 'Input Price ↓', + cardView: 'Card view', + listView: 'List view', + modelsCount: '{count} models available', + available: 'Available', + model: 'Model', + empty: 'No models available', + noPricing: 'No pricing configured', + input: 'Input', + output: 'Output', + cacheRead: 'Cache Read', + cacheWrite: 'Cache Write', + imageOutput: 'Image Output', + perRequest: 'Per Request', + unitPerMTok: '$/M tokens', + unitPerRequest: '$/request', + groups: 'Groups & Multipliers', + collapse: 'Collapse', + exclusiveGroup: 'Exclusive group', + publicGroup: 'Public group', + peakRate: 'Peak {start}-{end} ×{rate}', + customRate: 'Your custom rate' + } +} diff --git a/frontend/src/i18n/locales/zh/admin/channels.ts b/frontend/src/i18n/locales/zh/admin/channels.ts index 93890e25b055..87f174620911 100644 --- a/frontend/src/i18n/locales/zh/admin/channels.ts +++ b/frontend/src/i18n/locales/zh/admin/channels.ts @@ -462,6 +462,78 @@ export default { }, }, + // Scheduling Policies + schedulingPolicies: { + title: '调度策略', + description: '根据渠道监控结果自动临停/降级/恢复账号', + tabPolicies: '策略列表', + tabActions: '动作历史', + searchPlaceholder: '搜索策略名称...', + createButton: '新增策略', + createTitle: '新增调度策略', + editTitle: '编辑调度策略', + allPolicies: '全部策略', + accountsCount: '{count} 个账号', + failuresSummary: '连续失败 {count} 次', + latencySummary: '延迟 > {ms}ms', + pauseSummary: '临停 {minutes} 分钟', + pauseUntilRecoverySummary: '临停至恢复', + deprioritizeSummary: '优先级 +{delta}', + restored: '已恢复', + active: '生效中', + noPoliciesYet: '还没有调度策略', + createFirstPolicy: '创建第一条策略,让监控结果自动驱动账号调度', + noActionsYet: '还没有调度动作记录', + noActionsHint: '策略触发或恢复时会在这里留下审计记录', + loadError: '加载失败', + createSuccess: '策略创建成功', + updateSuccess: '策略更新成功', + deleteSuccess: '策略删除成功', + deleteConfirm: '确定要删除策略「{name}」吗?此操作不可撤销。', + monitorRequired: '请选择关联监控', + accountsRequired: '请至少选择一个账号', + actionKinds: { + pause: '临时停用', + deprioritize: '降低优先级', + recover: '恢复' + }, + columns: { + name: '名称', + monitor: '关联监控', + accounts: '目标账号', + condition: '触发条件', + action: '动作', + enabled: '启用', + actions: '操作', + policy: '策略', + account: '账号', + reason: '原因', + status: '状态', + time: '时间' + }, + form: { + name: '策略名称', + namePlaceholder: '输入策略名称', + monitor: '关联监控', + monitorPlaceholder: '选择渠道监控', + accounts: '目标账号', + noAccounts: '暂无可选账号', + consecutiveFailures: '连续失败次数', + latencyThreshold: '延迟阈值 (ms)', + latencyThresholdHint: '0 表示不按延迟触发', + actionType: '触发动作', + pauseMinutes: '临停时长 (分钟)', + pauseMinutesHint: '0 表示停用至满足恢复条件(30 天兜底)', + priorityDelta: '优先级增量', + priorityDeltaHint: '数值越大优先级越低,恢复时还原原值', + recoverSuccesses: '恢复所需连续成功次数', + recoverSuccessesHint: '0 表示不自动恢复,需手动处理', + cooldownMinutes: '冷却时间 (分钟)', + cooldownMinutesHint: '两次触发之间的最小间隔,防止频繁抖动', + enabled: '启用策略' + } + }, + // Channel Monitor channelMonitor: { title: '渠道监控', diff --git a/frontend/src/i18n/locales/zh/common.ts b/frontend/src/i18n/locales/zh/common.ts index 44fafef7a4ba..1ff93aefde63 100644 --- a/frontend/src/i18n/locales/zh/common.ts +++ b/frontend/src/i18n/locales/zh/common.ts @@ -163,6 +163,7 @@ export default { groups: '分组管理', channels: '渠道管理', availableChannels: '可用渠道', + modelPlaza: '模型广场', subscriptions: '订阅管理', accounts: '账号管理', proxies: 'IP管理', @@ -188,6 +189,7 @@ export default { channelManagement: '渠道管理', channelPricing: '渠道定价', channelMonitor: '渠道监控', + schedulingPolicies: '调度策略', channelStatus: '渠道状态', riskControl: '风控中心', }, diff --git a/frontend/src/i18n/locales/zh/index.ts b/frontend/src/i18n/locales/zh/index.ts index 377c67aec7c4..c408db418359 100644 --- a/frontend/src/i18n/locales/zh/index.ts +++ b/frontend/src/i18n/locales/zh/index.ts @@ -3,6 +3,7 @@ import common from './common' import dashboard from './dashboard' import admin from './admin' import misc from './misc' +import modelPlaza from './modelPlaza' export default { ...landing, @@ -10,4 +11,5 @@ export default { ...dashboard, admin, ...misc, + ...modelPlaza, } diff --git a/frontend/src/i18n/locales/zh/modelPlaza.ts b/frontend/src/i18n/locales/zh/modelPlaza.ts new file mode 100644 index 000000000000..6fa621787b78 --- /dev/null +++ b/frontend/src/i18n/locales/zh/modelPlaza.ts @@ -0,0 +1,39 @@ +export default { + modelPlaza: { + title: '模型广场', + description: '查看您可用分组的模型及官方定价', + bannerDescription: '探索可用模型的定价与分组信息', + searchPlaceholder: '搜索模型名称或提供商...', + allGroups: '全部分组', + provider: '提供商', + allProviders: '全部提供商', + type: '类型', + allTypes: '全部类型', + typeChat: '对话', + typePerRequest: '按次', + sortName: '模型名称', + sortInputAsc: '输入价格 ↑', + sortInputDesc: '输入价格 ↓', + cardView: '卡片视图', + listView: '列表视图', + modelsCount: '{count} 个可用模型', + available: '可用', + model: '模型', + empty: '暂无可用模型', + noPricing: '未配置定价', + input: '输入', + output: '输出', + cacheRead: 'Cache Read', + cacheWrite: 'Cache Write', + imageOutput: '图片输出', + perRequest: '每次请求', + unitPerMTok: '$/M tokens', + unitPerRequest: '$/次', + groups: '可用分组与倍率', + collapse: '收起', + exclusiveGroup: '专属分组', + publicGroup: '公开分组', + peakRate: '高峰 {start}-{end} ×{rate}', + customRate: '你的专属倍率' + } +} diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 306a0eac307f..653279ee9dc9 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -39,6 +39,18 @@ const routes: RouteRecordRaw[] = [ title: 'Home' } }, + { + path: '/models', + name: 'ModelPlaza', + component: () => import('@/views/user/ModelPlazaView.vue'), + meta: { + requiresAuth: true, + requiresAdmin: false, + title: 'Model Plaza', + titleKey: 'modelPlaza.title', + descriptionKey: 'modelPlaza.description' + } + }, { path: '/login', name: 'Login', @@ -467,6 +479,18 @@ const routes: RouteRecordRaw[] = [ descriptionKey: 'admin.channelMonitor.description' } }, + { + path: '/admin/scheduling-policies', + name: 'AdminSchedulingPolicies', + component: () => import('@/views/admin/SchedulingPoliciesView.vue'), + meta: { + requiresAuth: true, + requiresAdmin: true, + title: 'Scheduling Policies', + titleKey: 'admin.schedulingPolicies.title', + descriptionKey: 'admin.schedulingPolicies.description' + } + }, { path: '/monitor', name: 'ChannelStatus', diff --git a/frontend/src/views/admin/SchedulingPoliciesView.vue b/frontend/src/views/admin/SchedulingPoliciesView.vue new file mode 100644 index 000000000000..0ff0838e55f9 --- /dev/null +++ b/frontend/src/views/admin/SchedulingPoliciesView.vue @@ -0,0 +1,589 @@ + + + diff --git a/frontend/src/views/user/ModelPlazaView.vue b/frontend/src/views/user/ModelPlazaView.vue new file mode 100644 index 000000000000..24bfb5e42e38 --- /dev/null +++ b/frontend/src/views/user/ModelPlazaView.vue @@ -0,0 +1,636 @@ + + + + +