From 6d3fa6ab54d68f9451c88c38079eaf440935ab2f Mon Sep 17 00:00:00 2001 From: tycho garen Date: Wed, 5 Mar 2025 10:22:01 -0500 Subject: [PATCH 01/10] feat: persist sandboxes locally in orchestrator --- Makefile | 8 +- packages/orchestrator/internal/db/db.go | 99 ++ packages/orchestrator/internal/makefile | 4 + .../internal/pkg/generate_models.go | 3 + .../internal/pkg/models/client.go | 499 +++++++ .../orchestrator/internal/pkg/models/ent.go | 610 ++++++++ .../internal/pkg/models/enttest/enttest.go | 84 ++ .../internal/pkg/models/hook/hook.go | 211 +++ .../pkg/models/internal/schemaconfig.go | 25 + .../internal/pkg/models/migrate/migrate.go | 64 + .../internal/pkg/models/migrate/schema.go | 50 + .../internal/pkg/models/mutation.go | 1312 +++++++++++++++++ .../pkg/models/predicate/predicate.go | 13 + .../internal/pkg/models/runtime.go | 53 + .../internal/pkg/models/runtime/runtime.go | 10 + .../internal/pkg/models/sandbox.go | 189 +++ .../internal/pkg/models/sandbox/sandbox.go | 146 ++ .../internal/pkg/models/sandbox/where.go | 415 ++++++ .../internal/pkg/models/sandbox_create.go | 943 ++++++++++++ .../internal/pkg/models/sandbox_delete.go | 91 ++ .../internal/pkg/models/sandbox_query.go | 556 +++++++ .../internal/pkg/models/sandbox_update.go | 551 +++++++ .../internal/pkg/models/status.go | 128 ++ .../internal/pkg/models/status/status.go | 101 ++ .../internal/pkg/models/status/where.go | 180 +++ .../internal/pkg/models/status_create.go | 622 ++++++++ .../internal/pkg/models/status_delete.go | 91 ++ .../internal/pkg/models/status_query.go | 556 +++++++ .../internal/pkg/models/status_update.go | 355 +++++ .../orchestrator/internal/pkg/models/tx.go | 213 +++ .../internal/pkg/schema/sandbox.go | 32 + .../internal/pkg/schema/status.go | 22 + .../orchestrator/internal/sandbox/checks.go | 4 +- packages/orchestrator/internal/server/main.go | 46 +- .../orchestrator/internal/server/sandboxes.go | 53 +- 35 files changed, 8325 insertions(+), 14 deletions(-) create mode 100644 packages/orchestrator/internal/db/db.go create mode 100644 packages/orchestrator/internal/makefile create mode 100644 packages/orchestrator/internal/pkg/generate_models.go create mode 100644 packages/orchestrator/internal/pkg/models/client.go create mode 100644 packages/orchestrator/internal/pkg/models/ent.go create mode 100644 packages/orchestrator/internal/pkg/models/enttest/enttest.go create mode 100644 packages/orchestrator/internal/pkg/models/hook/hook.go create mode 100644 packages/orchestrator/internal/pkg/models/internal/schemaconfig.go create mode 100644 packages/orchestrator/internal/pkg/models/migrate/migrate.go create mode 100644 packages/orchestrator/internal/pkg/models/migrate/schema.go create mode 100644 packages/orchestrator/internal/pkg/models/mutation.go create mode 100644 packages/orchestrator/internal/pkg/models/predicate/predicate.go create mode 100644 packages/orchestrator/internal/pkg/models/runtime.go create mode 100644 packages/orchestrator/internal/pkg/models/runtime/runtime.go create mode 100644 packages/orchestrator/internal/pkg/models/sandbox.go create mode 100644 packages/orchestrator/internal/pkg/models/sandbox/sandbox.go create mode 100644 packages/orchestrator/internal/pkg/models/sandbox/where.go create mode 100644 packages/orchestrator/internal/pkg/models/sandbox_create.go create mode 100644 packages/orchestrator/internal/pkg/models/sandbox_delete.go create mode 100644 packages/orchestrator/internal/pkg/models/sandbox_query.go create mode 100644 packages/orchestrator/internal/pkg/models/sandbox_update.go create mode 100644 packages/orchestrator/internal/pkg/models/status.go create mode 100644 packages/orchestrator/internal/pkg/models/status/status.go create mode 100644 packages/orchestrator/internal/pkg/models/status/where.go create mode 100644 packages/orchestrator/internal/pkg/models/status_create.go create mode 100644 packages/orchestrator/internal/pkg/models/status_delete.go create mode 100644 packages/orchestrator/internal/pkg/models/status_query.go create mode 100644 packages/orchestrator/internal/pkg/models/status_update.go create mode 100644 packages/orchestrator/internal/pkg/models/tx.go create mode 100644 packages/orchestrator/internal/pkg/schema/sandbox.go create mode 100644 packages/orchestrator/internal/pkg/schema/status.go diff --git a/Makefile b/Makefile index a6bc918fa..bab2b2352 100644 --- a/Makefile +++ b/Makefile @@ -119,10 +119,16 @@ copy-public-builds: gsutil cp -r gs://e2b-prod-public-builds/kernels/* gs://$(GCP_PROJECT_ID)-fc-kernels/ gsutil cp -r gs://e2b-prod-public-builds/firecrackers/* gs://$(GCP_PROJECT_ID)-fc-versions/ -@.PHONY: migrate +.PHONY: migrate migrate: $(MAKE) -C packages/shared migrate +.PHONY: generate +generate:generate/orchestrator/internal +generate:generate/shared +generate/%: + $(MAKE) -C packages/$(subst generate/,,$@) generate-models + .PHONY: switch-env switch-env: @ touch .last_used_env diff --git a/packages/orchestrator/internal/db/db.go b/packages/orchestrator/internal/db/db.go new file mode 100644 index 000000000..44ce366cd --- /dev/null +++ b/packages/orchestrator/internal/db/db.go @@ -0,0 +1,99 @@ +package db + +import ( + "context" + "errors" + "time" + + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" +) + +type DB struct { + client *models.Client +} + +func (db *DB) Close() error { return db.client.Close() } + +func (db *DB) CreateSandbox(ctx context.Context, op func(*models.SandboxCreate)) error { + return db.WithTx(ctx, func(ctx context.Context) error { + now := time.Now() + tx := models.FromContext(ctx) + + global, err := tx.Status.UpdateOneID(1).AddVersion(1).SetUpdatedAt(now).Save(ctx) + if err != nil { + return err + } + + obj := tx.Sandbox.Create() + op(obj) + obj.SetVersion(1).SetGlobalVersion(global.Version).SetUpdatedAt(now) + if _, err := obj.Save(ctx); err != nil { + return err + } + + return nil + }) +} + +func (db *DB) UpdateSandbox(ctx context.Context, id string, op func(*models.SandboxUpdateOne)) error { + return db.WithTx(ctx, func(ctx context.Context) error { + now := time.Now() + tx := models.FromContext(ctx) + + global, err := tx.Status.UpdateOneID(1).AddVersion(1).SetUpdatedAt(now).Save(ctx) + if err != nil { + return err + } + + obj := tx.Sandbox.UpdateOneID(id) + if err != nil { + return err + } + + prev, err := tx.Sandbox.Get(ctx, id) + if err != nil { + return err + } + + op(obj) + obj = obj.SetUpdatedAt(now).SetGlobalVersion(global.Version).AddVersion(1) + switch prev.Status { + case sandbox.StatusPaused, sandbox.StatusPending, sandbox.StatusTerminated: + obj = obj.AddDurationMs(now.Sub(prev.UpdatedAt).Milliseconds()) + } + + if _, err := obj.Save(ctx); err != nil { + return err + } + + return nil + }) +} + +func (db *DB) WithTx(ctx context.Context, op func(context.Context) error) (err error) { + var tx *models.Tx + tx, err = db.client.Tx(ctx) + if err != nil { + return err + } + ctx = models.NewTxContext(ctx, tx) + defer func() { + if err != nil { + err = errors.Join(err, tx.Rollback()) + } + }() + defer func() { + if p := recover(); p != nil { + tx.Rollback() + panic(p) + } + }() + defer func() { + if err == nil { + err = tx.Commit() + } + }() + + return op(ctx) +} diff --git a/packages/orchestrator/internal/makefile b/packages/orchestrator/internal/makefile new file mode 100644 index 000000000..807aa0b6e --- /dev/null +++ b/packages/orchestrator/internal/makefile @@ -0,0 +1,4 @@ +.PHONY: generate-models +generate-models: + rm -rf pkg/models/* + go generate ./pkg/generate_models.go diff --git a/packages/orchestrator/internal/pkg/generate_models.go b/packages/orchestrator/internal/pkg/generate_models.go new file mode 100644 index 000000000..b6624c44a --- /dev/null +++ b/packages/orchestrator/internal/pkg/generate_models.go @@ -0,0 +1,3 @@ +package pkg + +//go:generate go run entgo.io/ent/cmd/ent generate --feature sql/schemaconfig,sql/upsert,sql/modifier ./schema --target ./models diff --git a/packages/orchestrator/internal/pkg/models/client.go b/packages/orchestrator/internal/pkg/models/client.go new file mode 100644 index 000000000..2f71ed25b --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/client.go @@ -0,0 +1,499 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/migrate" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" + + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // Sandbox is the client for interacting with the Sandbox builders. + Sandbox *SandboxClient + // Status is the client for interacting with the Status builders. + Status *StatusClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + client := &Client{config: newConfig(opts...)} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Sandbox = NewSandboxClient(c.config) + c.Status = NewStatusClient(c.config) +} + +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + // schemaConfig contains alternative names for all tables. + schemaConfig SchemaConfig + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("models: cannot start a transaction within a transaction") + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, ErrTxStarted + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("models: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + Sandbox: NewSandboxClient(cfg), + Status: NewStatusClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + Sandbox: NewSandboxClient(cfg), + Status: NewStatusClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Sandbox. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.Sandbox.Use(hooks...) + c.Status.Use(hooks...) +} + +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + c.Sandbox.Intercept(interceptors...) + c.Status.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *SandboxMutation: + return c.Sandbox.mutate(ctx, m) + case *StatusMutation: + return c.Status.mutate(ctx, m) + default: + return nil, fmt.Errorf("models: unknown mutation type %T", m) + } +} + +// SandboxClient is a client for the Sandbox schema. +type SandboxClient struct { + config +} + +// NewSandboxClient returns a client for the Sandbox from the given config. +func NewSandboxClient(c config) *SandboxClient { + return &SandboxClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `sandbox.Hooks(f(g(h())))`. +func (c *SandboxClient) Use(hooks ...Hook) { + c.hooks.Sandbox = append(c.hooks.Sandbox, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `sandbox.Intercept(f(g(h())))`. +func (c *SandboxClient) Intercept(interceptors ...Interceptor) { + c.inters.Sandbox = append(c.inters.Sandbox, interceptors...) +} + +// Create returns a builder for creating a Sandbox entity. +func (c *SandboxClient) Create() *SandboxCreate { + mutation := newSandboxMutation(c.config, OpCreate) + return &SandboxCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Sandbox entities. +func (c *SandboxClient) CreateBulk(builders ...*SandboxCreate) *SandboxCreateBulk { + return &SandboxCreateBulk{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 *SandboxClient) MapCreateBulk(slice any, setFunc func(*SandboxCreate, int)) *SandboxCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SandboxCreateBulk{err: fmt.Errorf("calling to SandboxClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SandboxCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SandboxCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Sandbox. +func (c *SandboxClient) Update() *SandboxUpdate { + mutation := newSandboxMutation(c.config, OpUpdate) + return &SandboxUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SandboxClient) UpdateOne(s *Sandbox) *SandboxUpdateOne { + mutation := newSandboxMutation(c.config, OpUpdateOne, withSandbox(s)) + return &SandboxUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SandboxClient) UpdateOneID(id string) *SandboxUpdateOne { + mutation := newSandboxMutation(c.config, OpUpdateOne, withSandboxID(id)) + return &SandboxUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Sandbox. +func (c *SandboxClient) Delete() *SandboxDelete { + mutation := newSandboxMutation(c.config, OpDelete) + return &SandboxDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SandboxClient) DeleteOne(s *Sandbox) *SandboxDeleteOne { + return c.DeleteOneID(s.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SandboxClient) DeleteOneID(id string) *SandboxDeleteOne { + builder := c.Delete().Where(sandbox.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SandboxDeleteOne{builder} +} + +// Query returns a query builder for Sandbox. +func (c *SandboxClient) Query() *SandboxQuery { + return &SandboxQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSandbox}, + inters: c.Interceptors(), + } +} + +// Get returns a Sandbox entity by its id. +func (c *SandboxClient) Get(ctx context.Context, id string) (*Sandbox, error) { + return c.Query().Where(sandbox.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SandboxClient) GetX(ctx context.Context, id string) *Sandbox { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *SandboxClient) Hooks() []Hook { + return c.hooks.Sandbox +} + +// Interceptors returns the client interceptors. +func (c *SandboxClient) Interceptors() []Interceptor { + return c.inters.Sandbox +} + +func (c *SandboxClient) mutate(ctx context.Context, m *SandboxMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SandboxCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SandboxUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SandboxUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SandboxDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Sandbox mutation op: %q", m.Op()) + } +} + +// StatusClient is a client for the Status schema. +type StatusClient struct { + config +} + +// NewStatusClient returns a client for the Status from the given config. +func NewStatusClient(c config) *StatusClient { + return &StatusClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `status.Hooks(f(g(h())))`. +func (c *StatusClient) Use(hooks ...Hook) { + c.hooks.Status = append(c.hooks.Status, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `status.Intercept(f(g(h())))`. +func (c *StatusClient) Intercept(interceptors ...Interceptor) { + c.inters.Status = append(c.inters.Status, interceptors...) +} + +// Create returns a builder for creating a Status entity. +func (c *StatusClient) Create() *StatusCreate { + mutation := newStatusMutation(c.config, OpCreate) + return &StatusCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Status entities. +func (c *StatusClient) CreateBulk(builders ...*StatusCreate) *StatusCreateBulk { + return &StatusCreateBulk{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 *StatusClient) MapCreateBulk(slice any, setFunc func(*StatusCreate, int)) *StatusCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &StatusCreateBulk{err: fmt.Errorf("calling to StatusClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*StatusCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &StatusCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Status. +func (c *StatusClient) Update() *StatusUpdate { + mutation := newStatusMutation(c.config, OpUpdate) + return &StatusUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *StatusClient) UpdateOne(s *Status) *StatusUpdateOne { + mutation := newStatusMutation(c.config, OpUpdateOne, withStatus(s)) + return &StatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *StatusClient) UpdateOneID(id int) *StatusUpdateOne { + mutation := newStatusMutation(c.config, OpUpdateOne, withStatusID(id)) + return &StatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Status. +func (c *StatusClient) Delete() *StatusDelete { + mutation := newStatusMutation(c.config, OpDelete) + return &StatusDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *StatusClient) DeleteOne(s *Status) *StatusDeleteOne { + return c.DeleteOneID(s.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *StatusClient) DeleteOneID(id int) *StatusDeleteOne { + builder := c.Delete().Where(status.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &StatusDeleteOne{builder} +} + +// Query returns a query builder for Status. +func (c *StatusClient) Query() *StatusQuery { + return &StatusQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeStatus}, + inters: c.Interceptors(), + } +} + +// Get returns a Status entity by its id. +func (c *StatusClient) Get(ctx context.Context, id int) (*Status, error) { + return c.Query().Where(status.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *StatusClient) GetX(ctx context.Context, id int) *Status { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *StatusClient) Hooks() []Hook { + return c.hooks.Status +} + +// Interceptors returns the client interceptors. +func (c *StatusClient) Interceptors() []Interceptor { + return c.inters.Status +} + +func (c *StatusClient) mutate(ctx context.Context, m *StatusMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&StatusCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&StatusUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&StatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&StatusDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Status mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Sandbox, Status []ent.Hook + } + inters struct { + Sandbox, Status []ent.Interceptor + } +) + +// SchemaConfig represents alternative schema names for all tables +// that can be passed at runtime. +type SchemaConfig = internal.SchemaConfig + +// AlternateSchemas allows alternate schema names to be +// passed into ent operations. +func AlternateSchema(schemaConfig SchemaConfig) Option { + return func(c *config) { + c.schemaConfig = schemaConfig + } +} diff --git a/packages/orchestrator/internal/pkg/models/ent.go b/packages/orchestrator/internal/pkg/models/ent.go new file mode 100644 index 000000000..dac90898d --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/ent.go @@ -0,0 +1,610 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "reflect" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// columnChecker checks if the column exists in the given table. +func checkColumn(table, column string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + sandbox.Table: sandbox.ValidColumn, + status.Table: status.ValidColumn, + }) + }) + return columnCheck(table, column) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(models.As(models.Sum(field1), "sum_field1"), (models.As(models.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "models: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "models: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "models: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "models: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/packages/orchestrator/internal/pkg/models/enttest/enttest.go b/packages/orchestrator/internal/pkg/models/enttest/enttest.go new file mode 100644 index 000000000..8c9f63c40 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/enttest/enttest.go @@ -0,0 +1,84 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" + // required by schema hooks. + _ "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/runtime" + + "entgo.io/ent/dialect/sql/schema" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/migrate" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []models.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...models.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls models.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *models.Client { + o := newOptions(opts) + c, err := models.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + migrateSchema(t, c, o) + return c +} + +// NewClient calls models.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *models.Client { + o := newOptions(opts) + c := models.NewClient(o.opts...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *models.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/packages/orchestrator/internal/pkg/models/hook/hook.go b/packages/orchestrator/internal/pkg/models/hook/hook.go new file mode 100644 index 000000000..8c677faad --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/hook/hook.go @@ -0,0 +1,211 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" +) + +// The SandboxFunc type is an adapter to allow the use of ordinary +// function as Sandbox mutator. +type SandboxFunc func(context.Context, *models.SandboxMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f SandboxFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.SandboxMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.SandboxMutation", m) +} + +// The StatusFunc type is an adapter to allow the use of ordinary +// function as Status mutator. +type StatusFunc func(context.Context, *models.StatusMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f StatusFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.StatusMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.StatusMutation", m) +} + +// Condition is a hook condition function. +type Condition func(context.Context, models.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op models.Op) Condition { + return func(_ context.Context, m models.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +func If(hk models.Hook, cond Condition) models.Hook { + return func(next models.Mutator) models.Mutator { + return models.MutateFunc(func(ctx context.Context, m models.Mutation) (models.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, models.Delete|models.Create) +func On(hk models.Hook, op models.Op) models.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, models.Update|models.UpdateOne) +func Unless(hk models.Hook, op models.Op) models.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) models.Hook { + return func(models.Mutator) models.Mutator { + return models.MutateFunc(func(context.Context, models.Mutation) (models.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []models.Hook { +// return []models.Hook{ +// Reject(models.Delete|models.Update), +// } +// } +func Reject(op models.Op) models.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []models.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...models.Hook) Chain { + return Chain{append([]models.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() models.Hook { + return func(mutator models.Mutator) models.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...models.Hook) Chain { + newHooks := make([]models.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/packages/orchestrator/internal/pkg/models/internal/schemaconfig.go b/packages/orchestrator/internal/pkg/models/internal/schemaconfig.go new file mode 100644 index 000000000..c4dbe072d --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/internal/schemaconfig.go @@ -0,0 +1,25 @@ +// Code generated by ent, DO NOT EDIT. + +package internal + +import "context" + +// SchemaConfig represents alternative schema names for all tables +// that can be passed at runtime. +type SchemaConfig struct { + Sandbox string // Sandbox table. + Status string // Status table. +} + +type schemaCtxKey struct{} + +// SchemaConfigFromContext returns a SchemaConfig stored inside a context, or empty if there isn't one. +func SchemaConfigFromContext(ctx context.Context) SchemaConfig { + config, _ := ctx.Value(schemaCtxKey{}).(SchemaConfig) + return config +} + +// NewSchemaConfigContext returns a new context with the given SchemaConfig attached. +func NewSchemaConfigContext(parent context.Context, config SchemaConfig) context.Context { + return context.WithValue(parent, schemaCtxKey{}, config) +} diff --git a/packages/orchestrator/internal/pkg/models/migrate/migrate.go b/packages/orchestrator/internal/pkg/models/migrate/migrate.go new file mode 100644 index 000000000..1956a6bf6 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/migrate/migrate.go @@ -0,0 +1,64 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/packages/orchestrator/internal/pkg/models/migrate/schema.go b/packages/orchestrator/internal/pkg/models/migrate/schema.go new file mode 100644 index 000000000..690460575 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/migrate/schema.go @@ -0,0 +1,50 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // SandboxesColumns holds the columns for the "sandboxes" table. + SandboxesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true}, + {Name: "started_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "terminated_at", Type: field.TypeTime}, + {Name: "deadline", Type: field.TypeTime}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"pending", "running", "paused", "terminated"}}, + {Name: "duration_ms", Type: field.TypeInt64}, + {Name: "version", Type: field.TypeInt64}, + {Name: "global_version", Type: field.TypeInt64}, + } + // SandboxesTable holds the schema information for the "sandboxes" table. + SandboxesTable = &schema.Table{ + Name: "sandboxes", + Columns: SandboxesColumns, + PrimaryKey: []*schema.Column{SandboxesColumns[0]}, + } + // StatusColumns holds the columns for the "status" table. + StatusColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "version", Type: field.TypeInt64, Unique: true}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"initializing", "running", "draining", "terminating"}, Default: "running"}, + } + // StatusTable holds the schema information for the "status" table. + StatusTable = &schema.Table{ + Name: "status", + Columns: StatusColumns, + PrimaryKey: []*schema.Column{StatusColumns[0]}, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + SandboxesTable, + StatusTable, + } +) + +func init() { +} diff --git a/packages/orchestrator/internal/pkg/models/mutation.go b/packages/orchestrator/internal/pkg/models/mutation.go new file mode 100644 index 000000000..8629fb3ef --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/mutation.go @@ -0,0 +1,1312 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeSandbox = "Sandbox" + TypeStatus = "Status" +) + +// SandboxMutation represents an operation that mutates the Sandbox nodes in the graph. +type SandboxMutation struct { + config + op Op + typ string + id *string + started_at *time.Time + updated_at *time.Time + terminated_at *time.Time + deadline *time.Time + status *sandbox.Status + duration_ms *int64 + addduration_ms *int64 + version *int64 + addversion *int64 + global_version *int64 + addglobal_version *int64 + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Sandbox, error) + predicates []predicate.Sandbox +} + +var _ ent.Mutation = (*SandboxMutation)(nil) + +// sandboxOption allows management of the mutation configuration using functional options. +type sandboxOption func(*SandboxMutation) + +// newSandboxMutation creates new mutation for the Sandbox entity. +func newSandboxMutation(c config, op Op, opts ...sandboxOption) *SandboxMutation { + m := &SandboxMutation{ + config: c, + op: op, + typ: TypeSandbox, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSandboxID sets the ID field of the mutation. +func withSandboxID(id string) sandboxOption { + return func(m *SandboxMutation) { + var ( + err error + once sync.Once + value *Sandbox + ) + m.oldValue = func(ctx context.Context) (*Sandbox, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Sandbox.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSandbox sets the old Sandbox of the mutation. +func withSandbox(node *Sandbox) sandboxOption { + return func(m *SandboxMutation) { + m.oldValue = func(context.Context) (*Sandbox, 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 SandboxMutation) 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 SandboxMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Sandbox entities. +func (m *SandboxMutation) SetID(id string) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *SandboxMutation) ID() (id string, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *SandboxMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Sandbox.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetStartedAt sets the "started_at" field. +func (m *SandboxMutation) SetStartedAt(t time.Time) { + m.started_at = &t +} + +// StartedAt returns the value of the "started_at" field in the mutation. +func (m *SandboxMutation) StartedAt() (r time.Time, exists bool) { + v := m.started_at + if v == nil { + return + } + return *v, true +} + +// OldStartedAt returns the old "started_at" field's value of the Sandbox entity. +// If the Sandbox 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 *SandboxMutation) OldStartedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStartedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStartedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStartedAt: %w", err) + } + return oldValue.StartedAt, nil +} + +// ResetStartedAt resets all changes to the "started_at" field. +func (m *SandboxMutation) ResetStartedAt() { + m.started_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *SandboxMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SandboxMutation) 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 Sandbox entity. +// If the Sandbox 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 *SandboxMutation) 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 *SandboxMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetTerminatedAt sets the "terminated_at" field. +func (m *SandboxMutation) SetTerminatedAt(t time.Time) { + m.terminated_at = &t +} + +// TerminatedAt returns the value of the "terminated_at" field in the mutation. +func (m *SandboxMutation) TerminatedAt() (r time.Time, exists bool) { + v := m.terminated_at + if v == nil { + return + } + return *v, true +} + +// OldTerminatedAt returns the old "terminated_at" field's value of the Sandbox entity. +// If the Sandbox 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 *SandboxMutation) OldTerminatedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTerminatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTerminatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTerminatedAt: %w", err) + } + return oldValue.TerminatedAt, nil +} + +// ResetTerminatedAt resets all changes to the "terminated_at" field. +func (m *SandboxMutation) ResetTerminatedAt() { + m.terminated_at = nil +} + +// SetDeadline sets the "deadline" field. +func (m *SandboxMutation) SetDeadline(t time.Time) { + m.deadline = &t +} + +// Deadline returns the value of the "deadline" field in the mutation. +func (m *SandboxMutation) Deadline() (r time.Time, exists bool) { + v := m.deadline + if v == nil { + return + } + return *v, true +} + +// OldDeadline returns the old "deadline" field's value of the Sandbox entity. +// If the Sandbox 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 *SandboxMutation) OldDeadline(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeadline is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeadline requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeadline: %w", err) + } + return oldValue.Deadline, nil +} + +// ResetDeadline resets all changes to the "deadline" field. +func (m *SandboxMutation) ResetDeadline() { + m.deadline = nil +} + +// SetStatus sets the "status" field. +func (m *SandboxMutation) SetStatus(s sandbox.Status) { + m.status = &s +} + +// Status returns the value of the "status" field in the mutation. +func (m *SandboxMutation) Status() (r sandbox.Status, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the Sandbox entity. +// If the Sandbox 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 *SandboxMutation) OldStatus(ctx context.Context) (v sandbox.Status, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *SandboxMutation) ResetStatus() { + m.status = nil +} + +// SetDurationMs sets the "duration_ms" field. +func (m *SandboxMutation) SetDurationMs(i int64) { + m.duration_ms = &i + m.addduration_ms = nil +} + +// DurationMs returns the value of the "duration_ms" field in the mutation. +func (m *SandboxMutation) DurationMs() (r int64, exists bool) { + v := m.duration_ms + if v == nil { + return + } + return *v, true +} + +// OldDurationMs returns the old "duration_ms" field's value of the Sandbox entity. +// If the Sandbox 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 *SandboxMutation) OldDurationMs(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDurationMs is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDurationMs requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDurationMs: %w", err) + } + return oldValue.DurationMs, nil +} + +// AddDurationMs adds i to the "duration_ms" field. +func (m *SandboxMutation) AddDurationMs(i int64) { + if m.addduration_ms != nil { + *m.addduration_ms += i + } else { + m.addduration_ms = &i + } +} + +// AddedDurationMs returns the value that was added to the "duration_ms" field in this mutation. +func (m *SandboxMutation) AddedDurationMs() (r int64, exists bool) { + v := m.addduration_ms + if v == nil { + return + } + return *v, true +} + +// ResetDurationMs resets all changes to the "duration_ms" field. +func (m *SandboxMutation) ResetDurationMs() { + m.duration_ms = nil + m.addduration_ms = nil +} + +// SetVersion sets the "version" field. +func (m *SandboxMutation) SetVersion(i int64) { + m.version = &i + m.addversion = nil +} + +// Version returns the value of the "version" field in the mutation. +func (m *SandboxMutation) Version() (r int64, exists bool) { + v := m.version + if v == nil { + return + } + return *v, true +} + +// OldVersion returns the old "version" field's value of the Sandbox entity. +// If the Sandbox 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 *SandboxMutation) OldVersion(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVersion: %w", err) + } + return oldValue.Version, nil +} + +// AddVersion adds i to the "version" field. +func (m *SandboxMutation) AddVersion(i int64) { + if m.addversion != nil { + *m.addversion += i + } else { + m.addversion = &i + } +} + +// AddedVersion returns the value that was added to the "version" field in this mutation. +func (m *SandboxMutation) AddedVersion() (r int64, exists bool) { + v := m.addversion + if v == nil { + return + } + return *v, true +} + +// ResetVersion resets all changes to the "version" field. +func (m *SandboxMutation) ResetVersion() { + m.version = nil + m.addversion = nil +} + +// SetGlobalVersion sets the "global_version" field. +func (m *SandboxMutation) SetGlobalVersion(i int64) { + m.global_version = &i + m.addglobal_version = nil +} + +// GlobalVersion returns the value of the "global_version" field in the mutation. +func (m *SandboxMutation) GlobalVersion() (r int64, exists bool) { + v := m.global_version + if v == nil { + return + } + return *v, true +} + +// OldGlobalVersion returns the old "global_version" field's value of the Sandbox entity. +// If the Sandbox 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 *SandboxMutation) OldGlobalVersion(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldGlobalVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldGlobalVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGlobalVersion: %w", err) + } + return oldValue.GlobalVersion, nil +} + +// AddGlobalVersion adds i to the "global_version" field. +func (m *SandboxMutation) AddGlobalVersion(i int64) { + if m.addglobal_version != nil { + *m.addglobal_version += i + } else { + m.addglobal_version = &i + } +} + +// AddedGlobalVersion returns the value that was added to the "global_version" field in this mutation. +func (m *SandboxMutation) AddedGlobalVersion() (r int64, exists bool) { + v := m.addglobal_version + if v == nil { + return + } + return *v, true +} + +// ResetGlobalVersion resets all changes to the "global_version" field. +func (m *SandboxMutation) ResetGlobalVersion() { + m.global_version = nil + m.addglobal_version = nil +} + +// Where appends a list predicates to the SandboxMutation builder. +func (m *SandboxMutation) Where(ps ...predicate.Sandbox) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SandboxMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SandboxMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Sandbox, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SandboxMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SandboxMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Sandbox). +func (m *SandboxMutation) 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 *SandboxMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.started_at != nil { + fields = append(fields, sandbox.FieldStartedAt) + } + if m.updated_at != nil { + fields = append(fields, sandbox.FieldUpdatedAt) + } + if m.terminated_at != nil { + fields = append(fields, sandbox.FieldTerminatedAt) + } + if m.deadline != nil { + fields = append(fields, sandbox.FieldDeadline) + } + if m.status != nil { + fields = append(fields, sandbox.FieldStatus) + } + if m.duration_ms != nil { + fields = append(fields, sandbox.FieldDurationMs) + } + if m.version != nil { + fields = append(fields, sandbox.FieldVersion) + } + if m.global_version != nil { + fields = append(fields, sandbox.FieldGlobalVersion) + } + 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 *SandboxMutation) Field(name string) (ent.Value, bool) { + switch name { + case sandbox.FieldStartedAt: + return m.StartedAt() + case sandbox.FieldUpdatedAt: + return m.UpdatedAt() + case sandbox.FieldTerminatedAt: + return m.TerminatedAt() + case sandbox.FieldDeadline: + return m.Deadline() + case sandbox.FieldStatus: + return m.Status() + case sandbox.FieldDurationMs: + return m.DurationMs() + case sandbox.FieldVersion: + return m.Version() + case sandbox.FieldGlobalVersion: + return m.GlobalVersion() + } + 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 *SandboxMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case sandbox.FieldStartedAt: + return m.OldStartedAt(ctx) + case sandbox.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case sandbox.FieldTerminatedAt: + return m.OldTerminatedAt(ctx) + case sandbox.FieldDeadline: + return m.OldDeadline(ctx) + case sandbox.FieldStatus: + return m.OldStatus(ctx) + case sandbox.FieldDurationMs: + return m.OldDurationMs(ctx) + case sandbox.FieldVersion: + return m.OldVersion(ctx) + case sandbox.FieldGlobalVersion: + return m.OldGlobalVersion(ctx) + } + return nil, fmt.Errorf("unknown Sandbox 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 *SandboxMutation) SetField(name string, value ent.Value) error { + switch name { + case sandbox.FieldStartedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStartedAt(v) + return nil + case sandbox.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 sandbox.FieldTerminatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTerminatedAt(v) + return nil + case sandbox.FieldDeadline: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeadline(v) + return nil + case sandbox.FieldStatus: + v, ok := value.(sandbox.Status) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case sandbox.FieldDurationMs: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDurationMs(v) + return nil + case sandbox.FieldVersion: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case sandbox.FieldGlobalVersion: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGlobalVersion(v) + return nil + } + return fmt.Errorf("unknown Sandbox field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SandboxMutation) AddedFields() []string { + var fields []string + if m.addduration_ms != nil { + fields = append(fields, sandbox.FieldDurationMs) + } + if m.addversion != nil { + fields = append(fields, sandbox.FieldVersion) + } + if m.addglobal_version != nil { + fields = append(fields, sandbox.FieldGlobalVersion) + } + 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 *SandboxMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case sandbox.FieldDurationMs: + return m.AddedDurationMs() + case sandbox.FieldVersion: + return m.AddedVersion() + case sandbox.FieldGlobalVersion: + return m.AddedGlobalVersion() + } + 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 *SandboxMutation) AddField(name string, value ent.Value) error { + switch name { + case sandbox.FieldDurationMs: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddDurationMs(v) + return nil + case sandbox.FieldVersion: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddVersion(v) + return nil + case sandbox.FieldGlobalVersion: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddGlobalVersion(v) + return nil + } + return fmt.Errorf("unknown Sandbox numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SandboxMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SandboxMutation) 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 *SandboxMutation) ClearField(name string) error { + return fmt.Errorf("unknown Sandbox 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 *SandboxMutation) ResetField(name string) error { + switch name { + case sandbox.FieldStartedAt: + m.ResetStartedAt() + return nil + case sandbox.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case sandbox.FieldTerminatedAt: + m.ResetTerminatedAt() + return nil + case sandbox.FieldDeadline: + m.ResetDeadline() + return nil + case sandbox.FieldStatus: + m.ResetStatus() + return nil + case sandbox.FieldDurationMs: + m.ResetDurationMs() + return nil + case sandbox.FieldVersion: + m.ResetVersion() + return nil + case sandbox.FieldGlobalVersion: + m.ResetGlobalVersion() + return nil + } + return fmt.Errorf("unknown Sandbox field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SandboxMutation) 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 *SandboxMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SandboxMutation) 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 *SandboxMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SandboxMutation) 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 *SandboxMutation) 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 *SandboxMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Sandbox 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 *SandboxMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Sandbox edge %s", name) +} + +// StatusMutation represents an operation that mutates the Status nodes in the graph. +type StatusMutation struct { + config + op Op + typ string + id *int + version *int64 + addversion *int64 + updated_at *time.Time + status *status.Status + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Status, error) + predicates []predicate.Status +} + +var _ ent.Mutation = (*StatusMutation)(nil) + +// statusOption allows management of the mutation configuration using functional options. +type statusOption func(*StatusMutation) + +// newStatusMutation creates new mutation for the Status entity. +func newStatusMutation(c config, op Op, opts ...statusOption) *StatusMutation { + m := &StatusMutation{ + config: c, + op: op, + typ: TypeStatus, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withStatusID sets the ID field of the mutation. +func withStatusID(id int) statusOption { + return func(m *StatusMutation) { + var ( + err error + once sync.Once + value *Status + ) + m.oldValue = func(ctx context.Context) (*Status, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Status.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withStatus sets the old Status of the mutation. +func withStatus(node *Status) statusOption { + return func(m *StatusMutation) { + m.oldValue = func(context.Context) (*Status, 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 StatusMutation) 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 StatusMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *StatusMutation) ID() (id int, 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 *StatusMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Status.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetVersion sets the "version" field. +func (m *StatusMutation) SetVersion(i int64) { + m.version = &i + m.addversion = nil +} + +// Version returns the value of the "version" field in the mutation. +func (m *StatusMutation) Version() (r int64, exists bool) { + v := m.version + if v == nil { + return + } + return *v, true +} + +// OldVersion returns the old "version" field's value of the Status entity. +// If the Status 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 *StatusMutation) OldVersion(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVersion: %w", err) + } + return oldValue.Version, nil +} + +// AddVersion adds i to the "version" field. +func (m *StatusMutation) AddVersion(i int64) { + if m.addversion != nil { + *m.addversion += i + } else { + m.addversion = &i + } +} + +// AddedVersion returns the value that was added to the "version" field in this mutation. +func (m *StatusMutation) AddedVersion() (r int64, exists bool) { + v := m.addversion + if v == nil { + return + } + return *v, true +} + +// ResetVersion resets all changes to the "version" field. +func (m *StatusMutation) ResetVersion() { + m.version = nil + m.addversion = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *StatusMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *StatusMutation) 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 Status entity. +// If the Status 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 *StatusMutation) 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 *StatusMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetStatus sets the "status" field. +func (m *StatusMutation) SetStatus(s status.Status) { + m.status = &s +} + +// Status returns the value of the "status" field in the mutation. +func (m *StatusMutation) Status() (r status.Status, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the Status entity. +// If the Status 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 *StatusMutation) OldStatus(ctx context.Context) (v status.Status, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *StatusMutation) ResetStatus() { + m.status = nil +} + +// Where appends a list predicates to the StatusMutation builder. +func (m *StatusMutation) Where(ps ...predicate.Status) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the StatusMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *StatusMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Status, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *StatusMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *StatusMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Status). +func (m *StatusMutation) 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 *StatusMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.version != nil { + fields = append(fields, status.FieldVersion) + } + if m.updated_at != nil { + fields = append(fields, status.FieldUpdatedAt) + } + if m.status != nil { + fields = append(fields, status.FieldStatus) + } + 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 *StatusMutation) Field(name string) (ent.Value, bool) { + switch name { + case status.FieldVersion: + return m.Version() + case status.FieldUpdatedAt: + return m.UpdatedAt() + case status.FieldStatus: + return m.Status() + } + 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 *StatusMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case status.FieldVersion: + return m.OldVersion(ctx) + case status.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case status.FieldStatus: + return m.OldStatus(ctx) + } + return nil, fmt.Errorf("unknown Status 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 *StatusMutation) SetField(name string, value ent.Value) error { + switch name { + case status.FieldVersion: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case status.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 status.FieldStatus: + v, ok := value.(status.Status) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + } + return fmt.Errorf("unknown Status field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *StatusMutation) AddedFields() []string { + var fields []string + if m.addversion != nil { + fields = append(fields, status.FieldVersion) + } + 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 *StatusMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case status.FieldVersion: + return m.AddedVersion() + } + 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 *StatusMutation) AddField(name string, value ent.Value) error { + switch name { + case status.FieldVersion: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddVersion(v) + return nil + } + return fmt.Errorf("unknown Status numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *StatusMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *StatusMutation) 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 *StatusMutation) ClearField(name string) error { + return fmt.Errorf("unknown Status 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 *StatusMutation) ResetField(name string) error { + switch name { + case status.FieldVersion: + m.ResetVersion() + return nil + case status.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case status.FieldStatus: + m.ResetStatus() + return nil + } + return fmt.Errorf("unknown Status field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *StatusMutation) 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 *StatusMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *StatusMutation) 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 *StatusMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *StatusMutation) 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 *StatusMutation) 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 *StatusMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Status 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 *StatusMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Status edge %s", name) +} diff --git a/packages/orchestrator/internal/pkg/models/predicate/predicate.go b/packages/orchestrator/internal/pkg/models/predicate/predicate.go new file mode 100644 index 000000000..a80ea017d --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/predicate/predicate.go @@ -0,0 +1,13 @@ +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Sandbox is the predicate function for sandbox builders. +type Sandbox func(*sql.Selector) + +// Status is the predicate function for status builders. +type Status func(*sql.Selector) diff --git a/packages/orchestrator/internal/pkg/models/runtime.go b/packages/orchestrator/internal/pkg/models/runtime.go new file mode 100644 index 000000000..c7b19ee1a --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/runtime.go @@ -0,0 +1,53 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "time" + + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/schema" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + sandboxFields := schema.Sandbox{}.Fields() + _ = sandboxFields + // sandboxDescStartedAt is the schema descriptor for started_at field. + sandboxDescStartedAt := sandboxFields[1].Descriptor() + // sandbox.DefaultStartedAt holds the default value on creation for the started_at field. + sandbox.DefaultStartedAt = sandboxDescStartedAt.Default.(func() time.Time) + // sandboxDescUpdatedAt is the schema descriptor for updated_at field. + sandboxDescUpdatedAt := sandboxFields[2].Descriptor() + // sandbox.DefaultUpdatedAt holds the default value on creation for the updated_at field. + sandbox.DefaultUpdatedAt = sandboxDescUpdatedAt.Default.(func() time.Time) + // sandboxDescDurationMs is the schema descriptor for duration_ms field. + sandboxDescDurationMs := sandboxFields[6].Descriptor() + // sandbox.DurationMsValidator is a validator for the "duration_ms" field. It is called by the builders before save. + sandbox.DurationMsValidator = sandboxDescDurationMs.Validators[0].(func(int64) error) + // sandboxDescVersion is the schema descriptor for version field. + sandboxDescVersion := sandboxFields[7].Descriptor() + // sandbox.VersionValidator is a validator for the "version" field. It is called by the builders before save. + sandbox.VersionValidator = sandboxDescVersion.Validators[0].(func(int64) error) + // sandboxDescGlobalVersion is the schema descriptor for global_version field. + sandboxDescGlobalVersion := sandboxFields[8].Descriptor() + // sandbox.GlobalVersionValidator is a validator for the "global_version" field. It is called by the builders before save. + sandbox.GlobalVersionValidator = sandboxDescGlobalVersion.Validators[0].(func(int64) error) + // sandboxDescID is the schema descriptor for id field. + sandboxDescID := sandboxFields[0].Descriptor() + // sandbox.IDValidator is a validator for the "id" field. It is called by the builders before save. + sandbox.IDValidator = sandboxDescID.Validators[0].(func(string) error) + statusFields := schema.Status{}.Fields() + _ = statusFields + // statusDescVersion is the schema descriptor for version field. + statusDescVersion := statusFields[0].Descriptor() + // status.VersionValidator is a validator for the "version" field. It is called by the builders before save. + status.VersionValidator = statusDescVersion.Validators[0].(func(int64) error) + // statusDescUpdatedAt is the schema descriptor for updated_at field. + statusDescUpdatedAt := statusFields[1].Descriptor() + // status.DefaultUpdatedAt holds the default value on creation for the updated_at field. + status.DefaultUpdatedAt = statusDescUpdatedAt.Default.(func() time.Time) +} diff --git a/packages/orchestrator/internal/pkg/models/runtime/runtime.go b/packages/orchestrator/internal/pkg/models/runtime/runtime.go new file mode 100644 index 000000000..6cebb1a95 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/runtime/runtime.go @@ -0,0 +1,10 @@ +// Code generated by ent, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/runtime.go + +const ( + Version = "v0.12.5" // Version of ent codegen. + Sum = "h1:KREM5E4CSoej4zeGa88Ou/gfturAnpUv0mzAjch1sj4=" // Sum of ent codegen. +) diff --git a/packages/orchestrator/internal/pkg/models/sandbox.go b/packages/orchestrator/internal/pkg/models/sandbox.go new file mode 100644 index 000000000..5050db168 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/sandbox.go @@ -0,0 +1,189 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" +) + +// Sandbox is the model entity for the Sandbox schema. +type Sandbox struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // StartedAt holds the value of the "started_at" field. + StartedAt time.Time `json:"started_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // TerminatedAt holds the value of the "terminated_at" field. + TerminatedAt *time.Time `json:"terminated_at,omitempty"` + // Deadline holds the value of the "deadline" field. + Deadline *time.Time `json:"deadline,omitempty"` + // Status holds the value of the "status" field. + Status sandbox.Status `json:"status,omitempty"` + // DurationMs holds the value of the "duration_ms" field. + DurationMs int64 `json:"duration_ms,omitempty"` + // an incrementing clock of this + Version int64 `json:"version,omitempty"` + // a record of the version of the global state of the last modification. + GlobalVersion int64 `json:"global_version,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Sandbox) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case sandbox.FieldDurationMs, sandbox.FieldVersion, sandbox.FieldGlobalVersion: + values[i] = new(sql.NullInt64) + case sandbox.FieldID, sandbox.FieldStatus: + values[i] = new(sql.NullString) + case sandbox.FieldStartedAt, sandbox.FieldUpdatedAt, sandbox.FieldTerminatedAt, sandbox.FieldDeadline: + 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 Sandbox fields. +func (s *Sandbox) 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 sandbox.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + s.ID = value.String + } + case sandbox.FieldStartedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field started_at", values[i]) + } else if value.Valid { + s.StartedAt = value.Time + } + case sandbox.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 { + s.UpdatedAt = value.Time + } + case sandbox.FieldTerminatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field terminated_at", values[i]) + } else if value.Valid { + s.TerminatedAt = new(time.Time) + *s.TerminatedAt = value.Time + } + case sandbox.FieldDeadline: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field deadline", values[i]) + } else if value.Valid { + s.Deadline = new(time.Time) + *s.Deadline = value.Time + } + case sandbox.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + s.Status = sandbox.Status(value.String) + } + case sandbox.FieldDurationMs: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field duration_ms", values[i]) + } else if value.Valid { + s.DurationMs = value.Int64 + } + case sandbox.FieldVersion: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field version", values[i]) + } else if value.Valid { + s.Version = value.Int64 + } + case sandbox.FieldGlobalVersion: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field global_version", values[i]) + } else if value.Valid { + s.GlobalVersion = value.Int64 + } + default: + s.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Sandbox. +// This includes values selected through modifiers, order, etc. +func (s *Sandbox) Value(name string) (ent.Value, error) { + return s.selectValues.Get(name) +} + +// Update returns a builder for updating this Sandbox. +// Note that you need to call Sandbox.Unwrap() before calling this method if this Sandbox +// was returned from a transaction, and the transaction was committed or rolled back. +func (s *Sandbox) Update() *SandboxUpdateOne { + return NewSandboxClient(s.config).UpdateOne(s) +} + +// Unwrap unwraps the Sandbox 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 (s *Sandbox) Unwrap() *Sandbox { + _tx, ok := s.config.driver.(*txDriver) + if !ok { + panic("models: Sandbox is not a transactional entity") + } + s.config.driver = _tx.drv + return s +} + +// String implements the fmt.Stringer. +func (s *Sandbox) String() string { + var builder strings.Builder + builder.WriteString("Sandbox(") + builder.WriteString(fmt.Sprintf("id=%v, ", s.ID)) + builder.WriteString("started_at=") + builder.WriteString(s.StartedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(s.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := s.TerminatedAt; v != nil { + builder.WriteString("terminated_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := s.Deadline; v != nil { + builder.WriteString("deadline=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", s.Status)) + builder.WriteString(", ") + builder.WriteString("duration_ms=") + builder.WriteString(fmt.Sprintf("%v", s.DurationMs)) + builder.WriteString(", ") + builder.WriteString("version=") + builder.WriteString(fmt.Sprintf("%v", s.Version)) + builder.WriteString(", ") + builder.WriteString("global_version=") + builder.WriteString(fmt.Sprintf("%v", s.GlobalVersion)) + builder.WriteByte(')') + return builder.String() +} + +// Sandboxes is a parsable slice of Sandbox. +type Sandboxes []*Sandbox diff --git a/packages/orchestrator/internal/pkg/models/sandbox/sandbox.go b/packages/orchestrator/internal/pkg/models/sandbox/sandbox.go new file mode 100644 index 000000000..837747820 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/sandbox/sandbox.go @@ -0,0 +1,146 @@ +// Code generated by ent, DO NOT EDIT. + +package sandbox + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the sandbox type in the database. + Label = "sandbox" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldStartedAt holds the string denoting the started_at field in the database. + FieldStartedAt = "started_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldTerminatedAt holds the string denoting the terminated_at field in the database. + FieldTerminatedAt = "terminated_at" + // FieldDeadline holds the string denoting the deadline field in the database. + FieldDeadline = "deadline" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldDurationMs holds the string denoting the duration_ms field in the database. + FieldDurationMs = "duration_ms" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldGlobalVersion holds the string denoting the global_version field in the database. + FieldGlobalVersion = "global_version" + // Table holds the table name of the sandbox in the database. + Table = "sandboxes" +) + +// Columns holds all SQL columns for sandbox fields. +var Columns = []string{ + FieldID, + FieldStartedAt, + FieldUpdatedAt, + FieldTerminatedAt, + FieldDeadline, + FieldStatus, + FieldDurationMs, + FieldVersion, + FieldGlobalVersion, +} + +// 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 ( + // DefaultStartedAt holds the default value on creation for the "started_at" field. + DefaultStartedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // DurationMsValidator is a validator for the "duration_ms" field. It is called by the builders before save. + DurationMsValidator func(int64) error + // VersionValidator is a validator for the "version" field. It is called by the builders before save. + VersionValidator func(int64) error + // GlobalVersionValidator is a validator for the "global_version" field. It is called by the builders before save. + GlobalVersionValidator func(int64) error + // IDValidator is a validator for the "id" field. It is called by the builders before save. + IDValidator func(string) error +) + +// Status defines the type for the "status" enum field. +type Status string + +// Status values. +const ( + StatusPending Status = "pending" + StatusRunning Status = "running" + StatusPaused Status = "paused" + StatusTerminated Status = "terminated" +) + +func (s Status) String() string { + return string(s) +} + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s Status) error { + switch s { + case StatusPending, StatusRunning, StatusPaused, StatusTerminated: + return nil + default: + return fmt.Errorf("sandbox: invalid enum value for status field: %q", s) + } +} + +// OrderOption defines the ordering options for the Sandbox 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() +} + +// ByStartedAt orders the results by the started_at field. +func ByStartedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStartedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByTerminatedAt orders the results by the terminated_at field. +func ByTerminatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTerminatedAt, opts...).ToFunc() +} + +// ByDeadline orders the results by the deadline field. +func ByDeadline(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeadline, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByDurationMs orders the results by the duration_ms field. +func ByDurationMs(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDurationMs, opts...).ToFunc() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByGlobalVersion orders the results by the global_version field. +func ByGlobalVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldGlobalVersion, opts...).ToFunc() +} diff --git a/packages/orchestrator/internal/pkg/models/sandbox/where.go b/packages/orchestrator/internal/pkg/models/sandbox/where.go new file mode 100644 index 000000000..db105d87a --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/sandbox/where.go @@ -0,0 +1,415 @@ +// Code generated by ent, DO NOT EDIT. + +package sandbox + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.Sandbox { + return predicate.Sandbox(sql.FieldContainsFold(FieldID, id)) +} + +// StartedAt applies equality check predicate on the "started_at" field. It's identical to StartedAtEQ. +func StartedAt(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldStartedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// TerminatedAt applies equality check predicate on the "terminated_at" field. It's identical to TerminatedAtEQ. +func TerminatedAt(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldTerminatedAt, v)) +} + +// Deadline applies equality check predicate on the "deadline" field. It's identical to DeadlineEQ. +func Deadline(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldDeadline, v)) +} + +// DurationMs applies equality check predicate on the "duration_ms" field. It's identical to DurationMsEQ. +func DurationMs(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldDurationMs, v)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldVersion, v)) +} + +// GlobalVersion applies equality check predicate on the "global_version" field. It's identical to GlobalVersionEQ. +func GlobalVersion(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldGlobalVersion, v)) +} + +// StartedAtEQ applies the EQ predicate on the "started_at" field. +func StartedAtEQ(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldStartedAt, v)) +} + +// StartedAtNEQ applies the NEQ predicate on the "started_at" field. +func StartedAtNEQ(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNEQ(FieldStartedAt, v)) +} + +// StartedAtIn applies the In predicate on the "started_at" field. +func StartedAtIn(vs ...time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldIn(FieldStartedAt, vs...)) +} + +// StartedAtNotIn applies the NotIn predicate on the "started_at" field. +func StartedAtNotIn(vs ...time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNotIn(FieldStartedAt, vs...)) +} + +// StartedAtGT applies the GT predicate on the "started_at" field. +func StartedAtGT(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGT(FieldStartedAt, v)) +} + +// StartedAtGTE applies the GTE predicate on the "started_at" field. +func StartedAtGTE(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGTE(FieldStartedAt, v)) +} + +// StartedAtLT applies the LT predicate on the "started_at" field. +func StartedAtLT(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLT(FieldStartedAt, v)) +} + +// StartedAtLTE applies the LTE predicate on the "started_at" field. +func StartedAtLTE(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLTE(FieldStartedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// TerminatedAtEQ applies the EQ predicate on the "terminated_at" field. +func TerminatedAtEQ(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldTerminatedAt, v)) +} + +// TerminatedAtNEQ applies the NEQ predicate on the "terminated_at" field. +func TerminatedAtNEQ(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNEQ(FieldTerminatedAt, v)) +} + +// TerminatedAtIn applies the In predicate on the "terminated_at" field. +func TerminatedAtIn(vs ...time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldIn(FieldTerminatedAt, vs...)) +} + +// TerminatedAtNotIn applies the NotIn predicate on the "terminated_at" field. +func TerminatedAtNotIn(vs ...time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNotIn(FieldTerminatedAt, vs...)) +} + +// TerminatedAtGT applies the GT predicate on the "terminated_at" field. +func TerminatedAtGT(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGT(FieldTerminatedAt, v)) +} + +// TerminatedAtGTE applies the GTE predicate on the "terminated_at" field. +func TerminatedAtGTE(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGTE(FieldTerminatedAt, v)) +} + +// TerminatedAtLT applies the LT predicate on the "terminated_at" field. +func TerminatedAtLT(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLT(FieldTerminatedAt, v)) +} + +// TerminatedAtLTE applies the LTE predicate on the "terminated_at" field. +func TerminatedAtLTE(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLTE(FieldTerminatedAt, v)) +} + +// DeadlineEQ applies the EQ predicate on the "deadline" field. +func DeadlineEQ(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldDeadline, v)) +} + +// DeadlineNEQ applies the NEQ predicate on the "deadline" field. +func DeadlineNEQ(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNEQ(FieldDeadline, v)) +} + +// DeadlineIn applies the In predicate on the "deadline" field. +func DeadlineIn(vs ...time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldIn(FieldDeadline, vs...)) +} + +// DeadlineNotIn applies the NotIn predicate on the "deadline" field. +func DeadlineNotIn(vs ...time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNotIn(FieldDeadline, vs...)) +} + +// DeadlineGT applies the GT predicate on the "deadline" field. +func DeadlineGT(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGT(FieldDeadline, v)) +} + +// DeadlineGTE applies the GTE predicate on the "deadline" field. +func DeadlineGTE(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGTE(FieldDeadline, v)) +} + +// DeadlineLT applies the LT predicate on the "deadline" field. +func DeadlineLT(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLT(FieldDeadline, v)) +} + +// DeadlineLTE applies the LTE predicate on the "deadline" field. +func DeadlineLTE(v time.Time) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLTE(FieldDeadline, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v Status) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldStatus, v)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v Status) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNEQ(FieldStatus, v)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...Status) predicate.Sandbox { + return predicate.Sandbox(sql.FieldIn(FieldStatus, vs...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...Status) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNotIn(FieldStatus, vs...)) +} + +// DurationMsEQ applies the EQ predicate on the "duration_ms" field. +func DurationMsEQ(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldDurationMs, v)) +} + +// DurationMsNEQ applies the NEQ predicate on the "duration_ms" field. +func DurationMsNEQ(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNEQ(FieldDurationMs, v)) +} + +// DurationMsIn applies the In predicate on the "duration_ms" field. +func DurationMsIn(vs ...int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldIn(FieldDurationMs, vs...)) +} + +// DurationMsNotIn applies the NotIn predicate on the "duration_ms" field. +func DurationMsNotIn(vs ...int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNotIn(FieldDurationMs, vs...)) +} + +// DurationMsGT applies the GT predicate on the "duration_ms" field. +func DurationMsGT(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGT(FieldDurationMs, v)) +} + +// DurationMsGTE applies the GTE predicate on the "duration_ms" field. +func DurationMsGTE(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGTE(FieldDurationMs, v)) +} + +// DurationMsLT applies the LT predicate on the "duration_ms" field. +func DurationMsLT(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLT(FieldDurationMs, v)) +} + +// DurationMsLTE applies the LTE predicate on the "duration_ms" field. +func DurationMsLTE(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLTE(FieldDurationMs, v)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLTE(FieldVersion, v)) +} + +// GlobalVersionEQ applies the EQ predicate on the "global_version" field. +func GlobalVersionEQ(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldEQ(FieldGlobalVersion, v)) +} + +// GlobalVersionNEQ applies the NEQ predicate on the "global_version" field. +func GlobalVersionNEQ(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNEQ(FieldGlobalVersion, v)) +} + +// GlobalVersionIn applies the In predicate on the "global_version" field. +func GlobalVersionIn(vs ...int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldIn(FieldGlobalVersion, vs...)) +} + +// GlobalVersionNotIn applies the NotIn predicate on the "global_version" field. +func GlobalVersionNotIn(vs ...int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldNotIn(FieldGlobalVersion, vs...)) +} + +// GlobalVersionGT applies the GT predicate on the "global_version" field. +func GlobalVersionGT(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGT(FieldGlobalVersion, v)) +} + +// GlobalVersionGTE applies the GTE predicate on the "global_version" field. +func GlobalVersionGTE(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldGTE(FieldGlobalVersion, v)) +} + +// GlobalVersionLT applies the LT predicate on the "global_version" field. +func GlobalVersionLT(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLT(FieldGlobalVersion, v)) +} + +// GlobalVersionLTE applies the LTE predicate on the "global_version" field. +func GlobalVersionLTE(v int64) predicate.Sandbox { + return predicate.Sandbox(sql.FieldLTE(FieldGlobalVersion, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Sandbox) predicate.Sandbox { + return predicate.Sandbox(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Sandbox) predicate.Sandbox { + return predicate.Sandbox(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Sandbox) predicate.Sandbox { + return predicate.Sandbox(sql.NotPredicates(p)) +} diff --git a/packages/orchestrator/internal/pkg/models/sandbox_create.go b/packages/orchestrator/internal/pkg/models/sandbox_create.go new file mode 100644 index 000000000..a951a1405 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/sandbox_create.go @@ -0,0 +1,943 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" +) + +// SandboxCreate is the builder for creating a Sandbox entity. +type SandboxCreate struct { + config + mutation *SandboxMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetStartedAt sets the "started_at" field. +func (sc *SandboxCreate) SetStartedAt(t time.Time) *SandboxCreate { + sc.mutation.SetStartedAt(t) + return sc +} + +// SetNillableStartedAt sets the "started_at" field if the given value is not nil. +func (sc *SandboxCreate) SetNillableStartedAt(t *time.Time) *SandboxCreate { + if t != nil { + sc.SetStartedAt(*t) + } + return sc +} + +// SetUpdatedAt sets the "updated_at" field. +func (sc *SandboxCreate) SetUpdatedAt(t time.Time) *SandboxCreate { + sc.mutation.SetUpdatedAt(t) + return sc +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (sc *SandboxCreate) SetNillableUpdatedAt(t *time.Time) *SandboxCreate { + if t != nil { + sc.SetUpdatedAt(*t) + } + return sc +} + +// SetTerminatedAt sets the "terminated_at" field. +func (sc *SandboxCreate) SetTerminatedAt(t time.Time) *SandboxCreate { + sc.mutation.SetTerminatedAt(t) + return sc +} + +// SetDeadline sets the "deadline" field. +func (sc *SandboxCreate) SetDeadline(t time.Time) *SandboxCreate { + sc.mutation.SetDeadline(t) + return sc +} + +// SetStatus sets the "status" field. +func (sc *SandboxCreate) SetStatus(s sandbox.Status) *SandboxCreate { + sc.mutation.SetStatus(s) + return sc +} + +// SetDurationMs sets the "duration_ms" field. +func (sc *SandboxCreate) SetDurationMs(i int64) *SandboxCreate { + sc.mutation.SetDurationMs(i) + return sc +} + +// SetVersion sets the "version" field. +func (sc *SandboxCreate) SetVersion(i int64) *SandboxCreate { + sc.mutation.SetVersion(i) + return sc +} + +// SetGlobalVersion sets the "global_version" field. +func (sc *SandboxCreate) SetGlobalVersion(i int64) *SandboxCreate { + sc.mutation.SetGlobalVersion(i) + return sc +} + +// SetID sets the "id" field. +func (sc *SandboxCreate) SetID(s string) *SandboxCreate { + sc.mutation.SetID(s) + return sc +} + +// Mutation returns the SandboxMutation object of the builder. +func (sc *SandboxCreate) Mutation() *SandboxMutation { + return sc.mutation +} + +// Save creates the Sandbox in the database. +func (sc *SandboxCreate) Save(ctx context.Context) (*Sandbox, error) { + sc.defaults() + return withHooks(ctx, sc.sqlSave, sc.mutation, sc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (sc *SandboxCreate) SaveX(ctx context.Context) *Sandbox { + v, err := sc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (sc *SandboxCreate) Exec(ctx context.Context) error { + _, err := sc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (sc *SandboxCreate) ExecX(ctx context.Context) { + if err := sc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (sc *SandboxCreate) defaults() { + if _, ok := sc.mutation.StartedAt(); !ok { + v := sandbox.DefaultStartedAt() + sc.mutation.SetStartedAt(v) + } + if _, ok := sc.mutation.UpdatedAt(); !ok { + v := sandbox.DefaultUpdatedAt() + sc.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (sc *SandboxCreate) check() error { + if _, ok := sc.mutation.StartedAt(); !ok { + return &ValidationError{Name: "started_at", err: errors.New(`models: missing required field "Sandbox.started_at"`)} + } + if _, ok := sc.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Sandbox.updated_at"`)} + } + if _, ok := sc.mutation.TerminatedAt(); !ok { + return &ValidationError{Name: "terminated_at", err: errors.New(`models: missing required field "Sandbox.terminated_at"`)} + } + if _, ok := sc.mutation.Deadline(); !ok { + return &ValidationError{Name: "deadline", err: errors.New(`models: missing required field "Sandbox.deadline"`)} + } + if _, ok := sc.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`models: missing required field "Sandbox.status"`)} + } + if v, ok := sc.mutation.Status(); ok { + if err := sandbox.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Sandbox.status": %w`, err)} + } + } + if _, ok := sc.mutation.DurationMs(); !ok { + return &ValidationError{Name: "duration_ms", err: errors.New(`models: missing required field "Sandbox.duration_ms"`)} + } + if v, ok := sc.mutation.DurationMs(); ok { + if err := sandbox.DurationMsValidator(v); err != nil { + return &ValidationError{Name: "duration_ms", err: fmt.Errorf(`models: validator failed for field "Sandbox.duration_ms": %w`, err)} + } + } + if _, ok := sc.mutation.Version(); !ok { + return &ValidationError{Name: "version", err: errors.New(`models: missing required field "Sandbox.version"`)} + } + if v, ok := sc.mutation.Version(); ok { + if err := sandbox.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Sandbox.version": %w`, err)} + } + } + if _, ok := sc.mutation.GlobalVersion(); !ok { + return &ValidationError{Name: "global_version", err: errors.New(`models: missing required field "Sandbox.global_version"`)} + } + if v, ok := sc.mutation.GlobalVersion(); ok { + if err := sandbox.GlobalVersionValidator(v); err != nil { + return &ValidationError{Name: "global_version", err: fmt.Errorf(`models: validator failed for field "Sandbox.global_version": %w`, err)} + } + } + if v, ok := sc.mutation.ID(); ok { + if err := sandbox.IDValidator(v); err != nil { + return &ValidationError{Name: "id", err: fmt.Errorf(`models: validator failed for field "Sandbox.id": %w`, err)} + } + } + return nil +} + +func (sc *SandboxCreate) sqlSave(ctx context.Context) (*Sandbox, error) { + if err := sc.check(); err != nil { + return nil, err + } + _node, _spec := sc.createSpec() + if err := sqlgraph.CreateNode(ctx, sc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected Sandbox.ID type: %T", _spec.ID.Value) + } + } + sc.mutation.id = &_node.ID + sc.mutation.done = true + return _node, nil +} + +func (sc *SandboxCreate) createSpec() (*Sandbox, *sqlgraph.CreateSpec) { + var ( + _node = &Sandbox{config: sc.config} + _spec = sqlgraph.NewCreateSpec(sandbox.Table, sqlgraph.NewFieldSpec(sandbox.FieldID, field.TypeString)) + ) + _spec.Schema = sc.schemaConfig.Sandbox + _spec.OnConflict = sc.conflict + if id, ok := sc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := sc.mutation.StartedAt(); ok { + _spec.SetField(sandbox.FieldStartedAt, field.TypeTime, value) + _node.StartedAt = value + } + if value, ok := sc.mutation.UpdatedAt(); ok { + _spec.SetField(sandbox.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := sc.mutation.TerminatedAt(); ok { + _spec.SetField(sandbox.FieldTerminatedAt, field.TypeTime, value) + _node.TerminatedAt = &value + } + if value, ok := sc.mutation.Deadline(); ok { + _spec.SetField(sandbox.FieldDeadline, field.TypeTime, value) + _node.Deadline = &value + } + if value, ok := sc.mutation.Status(); ok { + _spec.SetField(sandbox.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := sc.mutation.DurationMs(); ok { + _spec.SetField(sandbox.FieldDurationMs, field.TypeInt64, value) + _node.DurationMs = value + } + if value, ok := sc.mutation.Version(); ok { + _spec.SetField(sandbox.FieldVersion, field.TypeInt64, value) + _node.Version = value + } + if value, ok := sc.mutation.GlobalVersion(); ok { + _spec.SetField(sandbox.FieldGlobalVersion, field.TypeInt64, value) + _node.GlobalVersion = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Sandbox.Create(). +// SetStartedAt(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.SandboxUpsert) { +// SetStartedAt(v+v). +// }). +// Exec(ctx) +func (sc *SandboxCreate) OnConflict(opts ...sql.ConflictOption) *SandboxUpsertOne { + sc.conflict = opts + return &SandboxUpsertOne{ + create: sc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Sandbox.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (sc *SandboxCreate) OnConflictColumns(columns ...string) *SandboxUpsertOne { + sc.conflict = append(sc.conflict, sql.ConflictColumns(columns...)) + return &SandboxUpsertOne{ + create: sc, + } +} + +type ( + // SandboxUpsertOne is the builder for "upsert"-ing + // one Sandbox node. + SandboxUpsertOne struct { + create *SandboxCreate + } + + // SandboxUpsert is the "OnConflict" setter. + SandboxUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *SandboxUpsert) SetUpdatedAt(v time.Time) *SandboxUpsert { + u.Set(sandbox.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *SandboxUpsert) UpdateUpdatedAt() *SandboxUpsert { + u.SetExcluded(sandbox.FieldUpdatedAt) + return u +} + +// SetTerminatedAt sets the "terminated_at" field. +func (u *SandboxUpsert) SetTerminatedAt(v time.Time) *SandboxUpsert { + u.Set(sandbox.FieldTerminatedAt, v) + return u +} + +// UpdateTerminatedAt sets the "terminated_at" field to the value that was provided on create. +func (u *SandboxUpsert) UpdateTerminatedAt() *SandboxUpsert { + u.SetExcluded(sandbox.FieldTerminatedAt) + return u +} + +// SetDeadline sets the "deadline" field. +func (u *SandboxUpsert) SetDeadline(v time.Time) *SandboxUpsert { + u.Set(sandbox.FieldDeadline, v) + return u +} + +// UpdateDeadline sets the "deadline" field to the value that was provided on create. +func (u *SandboxUpsert) UpdateDeadline() *SandboxUpsert { + u.SetExcluded(sandbox.FieldDeadline) + return u +} + +// SetStatus sets the "status" field. +func (u *SandboxUpsert) SetStatus(v sandbox.Status) *SandboxUpsert { + u.Set(sandbox.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *SandboxUpsert) UpdateStatus() *SandboxUpsert { + u.SetExcluded(sandbox.FieldStatus) + return u +} + +// SetDurationMs sets the "duration_ms" field. +func (u *SandboxUpsert) SetDurationMs(v int64) *SandboxUpsert { + u.Set(sandbox.FieldDurationMs, v) + return u +} + +// UpdateDurationMs sets the "duration_ms" field to the value that was provided on create. +func (u *SandboxUpsert) UpdateDurationMs() *SandboxUpsert { + u.SetExcluded(sandbox.FieldDurationMs) + return u +} + +// AddDurationMs adds v to the "duration_ms" field. +func (u *SandboxUpsert) AddDurationMs(v int64) *SandboxUpsert { + u.Add(sandbox.FieldDurationMs, v) + return u +} + +// SetVersion sets the "version" field. +func (u *SandboxUpsert) SetVersion(v int64) *SandboxUpsert { + u.Set(sandbox.FieldVersion, v) + return u +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *SandboxUpsert) UpdateVersion() *SandboxUpsert { + u.SetExcluded(sandbox.FieldVersion) + return u +} + +// AddVersion adds v to the "version" field. +func (u *SandboxUpsert) AddVersion(v int64) *SandboxUpsert { + u.Add(sandbox.FieldVersion, v) + return u +} + +// SetGlobalVersion sets the "global_version" field. +func (u *SandboxUpsert) SetGlobalVersion(v int64) *SandboxUpsert { + u.Set(sandbox.FieldGlobalVersion, v) + return u +} + +// UpdateGlobalVersion sets the "global_version" field to the value that was provided on create. +func (u *SandboxUpsert) UpdateGlobalVersion() *SandboxUpsert { + u.SetExcluded(sandbox.FieldGlobalVersion) + return u +} + +// AddGlobalVersion adds v to the "global_version" field. +func (u *SandboxUpsert) AddGlobalVersion(v int64) *SandboxUpsert { + u.Add(sandbox.FieldGlobalVersion, v) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.Sandbox.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(sandbox.FieldID) +// }), +// ). +// Exec(ctx) +func (u *SandboxUpsertOne) UpdateNewValues() *SandboxUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(sandbox.FieldID) + } + if _, exists := u.create.mutation.StartedAt(); exists { + s.SetIgnore(sandbox.FieldStartedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Sandbox.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SandboxUpsertOne) Ignore() *SandboxUpsertOne { + 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 *SandboxUpsertOne) DoNothing() *SandboxUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SandboxCreate.OnConflict +// documentation for more info. +func (u *SandboxUpsertOne) Update(set func(*SandboxUpsert)) *SandboxUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SandboxUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *SandboxUpsertOne) SetUpdatedAt(v time.Time) *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *SandboxUpsertOne) UpdateUpdatedAt() *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetTerminatedAt sets the "terminated_at" field. +func (u *SandboxUpsertOne) SetTerminatedAt(v time.Time) *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.SetTerminatedAt(v) + }) +} + +// UpdateTerminatedAt sets the "terminated_at" field to the value that was provided on create. +func (u *SandboxUpsertOne) UpdateTerminatedAt() *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.UpdateTerminatedAt() + }) +} + +// SetDeadline sets the "deadline" field. +func (u *SandboxUpsertOne) SetDeadline(v time.Time) *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.SetDeadline(v) + }) +} + +// UpdateDeadline sets the "deadline" field to the value that was provided on create. +func (u *SandboxUpsertOne) UpdateDeadline() *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.UpdateDeadline() + }) +} + +// SetStatus sets the "status" field. +func (u *SandboxUpsertOne) SetStatus(v sandbox.Status) *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *SandboxUpsertOne) UpdateStatus() *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.UpdateStatus() + }) +} + +// SetDurationMs sets the "duration_ms" field. +func (u *SandboxUpsertOne) SetDurationMs(v int64) *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.SetDurationMs(v) + }) +} + +// AddDurationMs adds v to the "duration_ms" field. +func (u *SandboxUpsertOne) AddDurationMs(v int64) *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.AddDurationMs(v) + }) +} + +// UpdateDurationMs sets the "duration_ms" field to the value that was provided on create. +func (u *SandboxUpsertOne) UpdateDurationMs() *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.UpdateDurationMs() + }) +} + +// SetVersion sets the "version" field. +func (u *SandboxUpsertOne) SetVersion(v int64) *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.SetVersion(v) + }) +} + +// AddVersion adds v to the "version" field. +func (u *SandboxUpsertOne) AddVersion(v int64) *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.AddVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *SandboxUpsertOne) UpdateVersion() *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.UpdateVersion() + }) +} + +// SetGlobalVersion sets the "global_version" field. +func (u *SandboxUpsertOne) SetGlobalVersion(v int64) *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.SetGlobalVersion(v) + }) +} + +// AddGlobalVersion adds v to the "global_version" field. +func (u *SandboxUpsertOne) AddGlobalVersion(v int64) *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.AddGlobalVersion(v) + }) +} + +// UpdateGlobalVersion sets the "global_version" field to the value that was provided on create. +func (u *SandboxUpsertOne) UpdateGlobalVersion() *SandboxUpsertOne { + return u.Update(func(s *SandboxUpsert) { + s.UpdateGlobalVersion() + }) +} + +// Exec executes the query. +func (u *SandboxUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("models: missing options for SandboxCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SandboxUpsertOne) 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 *SandboxUpsertOne) ID(ctx context.Context) (id string, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("models: SandboxUpsertOne.ID is not supported by MySQL driver. Use SandboxUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *SandboxUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// SandboxCreateBulk is the builder for creating many Sandbox entities in bulk. +type SandboxCreateBulk struct { + config + err error + builders []*SandboxCreate + conflict []sql.ConflictOption +} + +// Save creates the Sandbox entities in the database. +func (scb *SandboxCreateBulk) Save(ctx context.Context) ([]*Sandbox, error) { + if scb.err != nil { + return nil, scb.err + } + specs := make([]*sqlgraph.CreateSpec, len(scb.builders)) + nodes := make([]*Sandbox, len(scb.builders)) + mutators := make([]Mutator, len(scb.builders)) + for i := range scb.builders { + func(i int, root context.Context) { + builder := scb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*SandboxMutation) + 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, scb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = scb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, scb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, scb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (scb *SandboxCreateBulk) SaveX(ctx context.Context) []*Sandbox { + v, err := scb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (scb *SandboxCreateBulk) Exec(ctx context.Context) error { + _, err := scb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (scb *SandboxCreateBulk) ExecX(ctx context.Context) { + if err := scb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Sandbox.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.SandboxUpsert) { +// SetStartedAt(v+v). +// }). +// Exec(ctx) +func (scb *SandboxCreateBulk) OnConflict(opts ...sql.ConflictOption) *SandboxUpsertBulk { + scb.conflict = opts + return &SandboxUpsertBulk{ + create: scb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Sandbox.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (scb *SandboxCreateBulk) OnConflictColumns(columns ...string) *SandboxUpsertBulk { + scb.conflict = append(scb.conflict, sql.ConflictColumns(columns...)) + return &SandboxUpsertBulk{ + create: scb, + } +} + +// SandboxUpsertBulk is the builder for "upsert"-ing +// a bulk of Sandbox nodes. +type SandboxUpsertBulk struct { + create *SandboxCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Sandbox.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(sandbox.FieldID) +// }), +// ). +// Exec(ctx) +func (u *SandboxUpsertBulk) UpdateNewValues() *SandboxUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(sandbox.FieldID) + } + if _, exists := b.mutation.StartedAt(); exists { + s.SetIgnore(sandbox.FieldStartedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Sandbox.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SandboxUpsertBulk) Ignore() *SandboxUpsertBulk { + 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 *SandboxUpsertBulk) DoNothing() *SandboxUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SandboxCreateBulk.OnConflict +// documentation for more info. +func (u *SandboxUpsertBulk) Update(set func(*SandboxUpsert)) *SandboxUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SandboxUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *SandboxUpsertBulk) SetUpdatedAt(v time.Time) *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *SandboxUpsertBulk) UpdateUpdatedAt() *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetTerminatedAt sets the "terminated_at" field. +func (u *SandboxUpsertBulk) SetTerminatedAt(v time.Time) *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.SetTerminatedAt(v) + }) +} + +// UpdateTerminatedAt sets the "terminated_at" field to the value that was provided on create. +func (u *SandboxUpsertBulk) UpdateTerminatedAt() *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.UpdateTerminatedAt() + }) +} + +// SetDeadline sets the "deadline" field. +func (u *SandboxUpsertBulk) SetDeadline(v time.Time) *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.SetDeadline(v) + }) +} + +// UpdateDeadline sets the "deadline" field to the value that was provided on create. +func (u *SandboxUpsertBulk) UpdateDeadline() *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.UpdateDeadline() + }) +} + +// SetStatus sets the "status" field. +func (u *SandboxUpsertBulk) SetStatus(v sandbox.Status) *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *SandboxUpsertBulk) UpdateStatus() *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.UpdateStatus() + }) +} + +// SetDurationMs sets the "duration_ms" field. +func (u *SandboxUpsertBulk) SetDurationMs(v int64) *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.SetDurationMs(v) + }) +} + +// AddDurationMs adds v to the "duration_ms" field. +func (u *SandboxUpsertBulk) AddDurationMs(v int64) *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.AddDurationMs(v) + }) +} + +// UpdateDurationMs sets the "duration_ms" field to the value that was provided on create. +func (u *SandboxUpsertBulk) UpdateDurationMs() *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.UpdateDurationMs() + }) +} + +// SetVersion sets the "version" field. +func (u *SandboxUpsertBulk) SetVersion(v int64) *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.SetVersion(v) + }) +} + +// AddVersion adds v to the "version" field. +func (u *SandboxUpsertBulk) AddVersion(v int64) *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.AddVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *SandboxUpsertBulk) UpdateVersion() *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.UpdateVersion() + }) +} + +// SetGlobalVersion sets the "global_version" field. +func (u *SandboxUpsertBulk) SetGlobalVersion(v int64) *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.SetGlobalVersion(v) + }) +} + +// AddGlobalVersion adds v to the "global_version" field. +func (u *SandboxUpsertBulk) AddGlobalVersion(v int64) *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.AddGlobalVersion(v) + }) +} + +// UpdateGlobalVersion sets the "global_version" field to the value that was provided on create. +func (u *SandboxUpsertBulk) UpdateGlobalVersion() *SandboxUpsertBulk { + return u.Update(func(s *SandboxUpsert) { + s.UpdateGlobalVersion() + }) +} + +// Exec executes the query. +func (u *SandboxUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("models: OnConflict was set for builder %d. Set it on the SandboxCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("models: missing options for SandboxCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SandboxUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/packages/orchestrator/internal/pkg/models/sandbox_delete.go b/packages/orchestrator/internal/pkg/models/sandbox_delete.go new file mode 100644 index 000000000..375a71859 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/sandbox_delete.go @@ -0,0 +1,91 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" +) + +// SandboxDelete is the builder for deleting a Sandbox entity. +type SandboxDelete struct { + config + hooks []Hook + mutation *SandboxMutation +} + +// Where appends a list predicates to the SandboxDelete builder. +func (sd *SandboxDelete) Where(ps ...predicate.Sandbox) *SandboxDelete { + sd.mutation.Where(ps...) + return sd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (sd *SandboxDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, sd.sqlExec, sd.mutation, sd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (sd *SandboxDelete) ExecX(ctx context.Context) int { + n, err := sd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (sd *SandboxDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(sandbox.Table, sqlgraph.NewFieldSpec(sandbox.FieldID, field.TypeString)) + _spec.Node.Schema = sd.schemaConfig.Sandbox + ctx = internal.NewSchemaConfigContext(ctx, sd.schemaConfig) + if ps := sd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, sd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + sd.mutation.done = true + return affected, err +} + +// SandboxDeleteOne is the builder for deleting a single Sandbox entity. +type SandboxDeleteOne struct { + sd *SandboxDelete +} + +// Where appends a list predicates to the SandboxDelete builder. +func (sdo *SandboxDeleteOne) Where(ps ...predicate.Sandbox) *SandboxDeleteOne { + sdo.sd.mutation.Where(ps...) + return sdo +} + +// Exec executes the deletion query. +func (sdo *SandboxDeleteOne) Exec(ctx context.Context) error { + n, err := sdo.sd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{sandbox.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (sdo *SandboxDeleteOne) ExecX(ctx context.Context) { + if err := sdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/packages/orchestrator/internal/pkg/models/sandbox_query.go b/packages/orchestrator/internal/pkg/models/sandbox_query.go new file mode 100644 index 000000000..8bd700649 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/sandbox_query.go @@ -0,0 +1,556 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" +) + +// SandboxQuery is the builder for querying Sandbox entities. +type SandboxQuery struct { + config + ctx *QueryContext + order []sandbox.OrderOption + inters []Interceptor + predicates []predicate.Sandbox + 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 SandboxQuery builder. +func (sq *SandboxQuery) Where(ps ...predicate.Sandbox) *SandboxQuery { + sq.predicates = append(sq.predicates, ps...) + return sq +} + +// Limit the number of records to be returned by this query. +func (sq *SandboxQuery) Limit(limit int) *SandboxQuery { + sq.ctx.Limit = &limit + return sq +} + +// Offset to start from. +func (sq *SandboxQuery) Offset(offset int) *SandboxQuery { + sq.ctx.Offset = &offset + return sq +} + +// 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 (sq *SandboxQuery) Unique(unique bool) *SandboxQuery { + sq.ctx.Unique = &unique + return sq +} + +// Order specifies how the records should be ordered. +func (sq *SandboxQuery) Order(o ...sandbox.OrderOption) *SandboxQuery { + sq.order = append(sq.order, o...) + return sq +} + +// First returns the first Sandbox entity from the query. +// Returns a *NotFoundError when no Sandbox was found. +func (sq *SandboxQuery) First(ctx context.Context) (*Sandbox, error) { + nodes, err := sq.Limit(1).All(setContextOp(ctx, sq.ctx, "First")) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{sandbox.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (sq *SandboxQuery) FirstX(ctx context.Context) *Sandbox { + node, err := sq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Sandbox ID from the query. +// Returns a *NotFoundError when no Sandbox ID was found. +func (sq *SandboxQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = sq.Limit(1).IDs(setContextOp(ctx, sq.ctx, "FirstID")); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{sandbox.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (sq *SandboxQuery) FirstIDX(ctx context.Context) string { + id, err := sq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Sandbox entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Sandbox entity is found. +// Returns a *NotFoundError when no Sandbox entities are found. +func (sq *SandboxQuery) Only(ctx context.Context) (*Sandbox, error) { + nodes, err := sq.Limit(2).All(setContextOp(ctx, sq.ctx, "Only")) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{sandbox.Label} + default: + return nil, &NotSingularError{sandbox.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (sq *SandboxQuery) OnlyX(ctx context.Context) *Sandbox { + node, err := sq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Sandbox ID in the query. +// Returns a *NotSingularError when more than one Sandbox ID is found. +// Returns a *NotFoundError when no entities are found. +func (sq *SandboxQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = sq.Limit(2).IDs(setContextOp(ctx, sq.ctx, "OnlyID")); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{sandbox.Label} + default: + err = &NotSingularError{sandbox.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (sq *SandboxQuery) OnlyIDX(ctx context.Context) string { + id, err := sq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Sandboxes. +func (sq *SandboxQuery) All(ctx context.Context) ([]*Sandbox, error) { + ctx = setContextOp(ctx, sq.ctx, "All") + if err := sq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Sandbox, *SandboxQuery]() + return withInterceptors[[]*Sandbox](ctx, sq, qr, sq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (sq *SandboxQuery) AllX(ctx context.Context) []*Sandbox { + nodes, err := sq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Sandbox IDs. +func (sq *SandboxQuery) IDs(ctx context.Context) (ids []string, err error) { + if sq.ctx.Unique == nil && sq.path != nil { + sq.Unique(true) + } + ctx = setContextOp(ctx, sq.ctx, "IDs") + if err = sq.Select(sandbox.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (sq *SandboxQuery) IDsX(ctx context.Context) []string { + ids, err := sq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (sq *SandboxQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, sq.ctx, "Count") + if err := sq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, sq, querierCount[*SandboxQuery](), sq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (sq *SandboxQuery) CountX(ctx context.Context) int { + count, err := sq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (sq *SandboxQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, sq.ctx, "Exist") + switch _, err := sq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (sq *SandboxQuery) ExistX(ctx context.Context) bool { + exist, err := sq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the SandboxQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (sq *SandboxQuery) Clone() *SandboxQuery { + if sq == nil { + return nil + } + return &SandboxQuery{ + config: sq.config, + ctx: sq.ctx.Clone(), + order: append([]sandbox.OrderOption{}, sq.order...), + inters: append([]Interceptor{}, sq.inters...), + predicates: append([]predicate.Sandbox{}, sq.predicates...), + // clone intermediate query. + sql: sq.sql.Clone(), + path: sq.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 { +// StartedAt time.Time `json:"started_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Sandbox.Query(). +// GroupBy(sandbox.FieldStartedAt). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (sq *SandboxQuery) GroupBy(field string, fields ...string) *SandboxGroupBy { + sq.ctx.Fields = append([]string{field}, fields...) + grbuild := &SandboxGroupBy{build: sq} + grbuild.flds = &sq.ctx.Fields + grbuild.label = sandbox.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 { +// StartedAt time.Time `json:"started_at,omitempty"` +// } +// +// client.Sandbox.Query(). +// Select(sandbox.FieldStartedAt). +// Scan(ctx, &v) +func (sq *SandboxQuery) Select(fields ...string) *SandboxSelect { + sq.ctx.Fields = append(sq.ctx.Fields, fields...) + sbuild := &SandboxSelect{SandboxQuery: sq} + sbuild.label = sandbox.Label + sbuild.flds, sbuild.scan = &sq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a SandboxSelect configured with the given aggregations. +func (sq *SandboxQuery) Aggregate(fns ...AggregateFunc) *SandboxSelect { + return sq.Select().Aggregate(fns...) +} + +func (sq *SandboxQuery) prepareQuery(ctx context.Context) error { + for _, inter := range sq.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, sq); err != nil { + return err + } + } + } + for _, f := range sq.ctx.Fields { + if !sandbox.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if sq.path != nil { + prev, err := sq.path(ctx) + if err != nil { + return err + } + sq.sql = prev + } + return nil +} + +func (sq *SandboxQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Sandbox, error) { + var ( + nodes = []*Sandbox{} + _spec = sq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Sandbox).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Sandbox{config: sq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + _spec.Node.Schema = sq.schemaConfig.Sandbox + ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) + if len(sq.modifiers) > 0 { + _spec.Modifiers = sq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, sq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (sq *SandboxQuery) sqlCount(ctx context.Context) (int, error) { + _spec := sq.querySpec() + _spec.Node.Schema = sq.schemaConfig.Sandbox + ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) + if len(sq.modifiers) > 0 { + _spec.Modifiers = sq.modifiers + } + _spec.Node.Columns = sq.ctx.Fields + if len(sq.ctx.Fields) > 0 { + _spec.Unique = sq.ctx.Unique != nil && *sq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, sq.driver, _spec) +} + +func (sq *SandboxQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(sandbox.Table, sandbox.Columns, sqlgraph.NewFieldSpec(sandbox.FieldID, field.TypeString)) + _spec.From = sq.sql + if unique := sq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if sq.path != nil { + _spec.Unique = true + } + if fields := sq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, sandbox.FieldID) + for i := range fields { + if fields[i] != sandbox.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := sq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := sq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := sq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := sq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (sq *SandboxQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(sq.driver.Dialect()) + t1 := builder.Table(sandbox.Table) + columns := sq.ctx.Fields + if len(columns) == 0 { + columns = sandbox.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if sq.sql != nil { + selector = sq.sql + selector.Select(selector.Columns(columns...)...) + } + if sq.ctx.Unique != nil && *sq.ctx.Unique { + selector.Distinct() + } + t1.Schema(sq.schemaConfig.Sandbox) + ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) + selector.WithContext(ctx) + for _, m := range sq.modifiers { + m(selector) + } + for _, p := range sq.predicates { + p(selector) + } + for _, p := range sq.order { + p(selector) + } + if offset := sq.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 := sq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (sq *SandboxQuery) Modify(modifiers ...func(s *sql.Selector)) *SandboxSelect { + sq.modifiers = append(sq.modifiers, modifiers...) + return sq.Select() +} + +// SandboxGroupBy is the group-by builder for Sandbox entities. +type SandboxGroupBy struct { + selector + build *SandboxQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (sgb *SandboxGroupBy) Aggregate(fns ...AggregateFunc) *SandboxGroupBy { + sgb.fns = append(sgb.fns, fns...) + return sgb +} + +// Scan applies the selector query and scans the result into the given value. +func (sgb *SandboxGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, sgb.build.ctx, "GroupBy") + if err := sgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SandboxQuery, *SandboxGroupBy](ctx, sgb.build, sgb, sgb.build.inters, v) +} + +func (sgb *SandboxGroupBy) sqlScan(ctx context.Context, root *SandboxQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(sgb.fns)) + for _, fn := range sgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*sgb.flds)+len(sgb.fns)) + for _, f := range *sgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*sgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := sgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// SandboxSelect is the builder for selecting fields of Sandbox entities. +type SandboxSelect struct { + *SandboxQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ss *SandboxSelect) Aggregate(fns ...AggregateFunc) *SandboxSelect { + ss.fns = append(ss.fns, fns...) + return ss +} + +// Scan applies the selector query and scans the result into the given value. +func (ss *SandboxSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ss.ctx, "Select") + if err := ss.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SandboxQuery, *SandboxSelect](ctx, ss.SandboxQuery, ss, ss.inters, v) +} + +func (ss *SandboxSelect) sqlScan(ctx context.Context, root *SandboxQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ss.fns)) + for _, fn := range ss.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ss.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 := ss.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (ss *SandboxSelect) Modify(modifiers ...func(s *sql.Selector)) *SandboxSelect { + ss.modifiers = append(ss.modifiers, modifiers...) + return ss +} diff --git a/packages/orchestrator/internal/pkg/models/sandbox_update.go b/packages/orchestrator/internal/pkg/models/sandbox_update.go new file mode 100644 index 000000000..3b9dd987e --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/sandbox_update.go @@ -0,0 +1,551 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" +) + +// SandboxUpdate is the builder for updating Sandbox entities. +type SandboxUpdate struct { + config + hooks []Hook + mutation *SandboxMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the SandboxUpdate builder. +func (su *SandboxUpdate) Where(ps ...predicate.Sandbox) *SandboxUpdate { + su.mutation.Where(ps...) + return su +} + +// SetUpdatedAt sets the "updated_at" field. +func (su *SandboxUpdate) SetUpdatedAt(t time.Time) *SandboxUpdate { + su.mutation.SetUpdatedAt(t) + return su +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (su *SandboxUpdate) SetNillableUpdatedAt(t *time.Time) *SandboxUpdate { + if t != nil { + su.SetUpdatedAt(*t) + } + return su +} + +// SetTerminatedAt sets the "terminated_at" field. +func (su *SandboxUpdate) SetTerminatedAt(t time.Time) *SandboxUpdate { + su.mutation.SetTerminatedAt(t) + return su +} + +// SetNillableTerminatedAt sets the "terminated_at" field if the given value is not nil. +func (su *SandboxUpdate) SetNillableTerminatedAt(t *time.Time) *SandboxUpdate { + if t != nil { + su.SetTerminatedAt(*t) + } + return su +} + +// SetDeadline sets the "deadline" field. +func (su *SandboxUpdate) SetDeadline(t time.Time) *SandboxUpdate { + su.mutation.SetDeadline(t) + return su +} + +// SetNillableDeadline sets the "deadline" field if the given value is not nil. +func (su *SandboxUpdate) SetNillableDeadline(t *time.Time) *SandboxUpdate { + if t != nil { + su.SetDeadline(*t) + } + return su +} + +// SetStatus sets the "status" field. +func (su *SandboxUpdate) SetStatus(s sandbox.Status) *SandboxUpdate { + su.mutation.SetStatus(s) + return su +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (su *SandboxUpdate) SetNillableStatus(s *sandbox.Status) *SandboxUpdate { + if s != nil { + su.SetStatus(*s) + } + return su +} + +// SetDurationMs sets the "duration_ms" field. +func (su *SandboxUpdate) SetDurationMs(i int64) *SandboxUpdate { + su.mutation.ResetDurationMs() + su.mutation.SetDurationMs(i) + return su +} + +// SetNillableDurationMs sets the "duration_ms" field if the given value is not nil. +func (su *SandboxUpdate) SetNillableDurationMs(i *int64) *SandboxUpdate { + if i != nil { + su.SetDurationMs(*i) + } + return su +} + +// AddDurationMs adds i to the "duration_ms" field. +func (su *SandboxUpdate) AddDurationMs(i int64) *SandboxUpdate { + su.mutation.AddDurationMs(i) + return su +} + +// SetVersion sets the "version" field. +func (su *SandboxUpdate) SetVersion(i int64) *SandboxUpdate { + su.mutation.ResetVersion() + su.mutation.SetVersion(i) + return su +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (su *SandboxUpdate) SetNillableVersion(i *int64) *SandboxUpdate { + if i != nil { + su.SetVersion(*i) + } + return su +} + +// AddVersion adds i to the "version" field. +func (su *SandboxUpdate) AddVersion(i int64) *SandboxUpdate { + su.mutation.AddVersion(i) + return su +} + +// SetGlobalVersion sets the "global_version" field. +func (su *SandboxUpdate) SetGlobalVersion(i int64) *SandboxUpdate { + su.mutation.ResetGlobalVersion() + su.mutation.SetGlobalVersion(i) + return su +} + +// SetNillableGlobalVersion sets the "global_version" field if the given value is not nil. +func (su *SandboxUpdate) SetNillableGlobalVersion(i *int64) *SandboxUpdate { + if i != nil { + su.SetGlobalVersion(*i) + } + return su +} + +// AddGlobalVersion adds i to the "global_version" field. +func (su *SandboxUpdate) AddGlobalVersion(i int64) *SandboxUpdate { + su.mutation.AddGlobalVersion(i) + return su +} + +// Mutation returns the SandboxMutation object of the builder. +func (su *SandboxUpdate) Mutation() *SandboxMutation { + return su.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (su *SandboxUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, su.sqlSave, su.mutation, su.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (su *SandboxUpdate) SaveX(ctx context.Context) int { + affected, err := su.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (su *SandboxUpdate) Exec(ctx context.Context) error { + _, err := su.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (su *SandboxUpdate) ExecX(ctx context.Context) { + if err := su.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (su *SandboxUpdate) check() error { + if v, ok := su.mutation.Status(); ok { + if err := sandbox.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Sandbox.status": %w`, err)} + } + } + if v, ok := su.mutation.DurationMs(); ok { + if err := sandbox.DurationMsValidator(v); err != nil { + return &ValidationError{Name: "duration_ms", err: fmt.Errorf(`models: validator failed for field "Sandbox.duration_ms": %w`, err)} + } + } + if v, ok := su.mutation.Version(); ok { + if err := sandbox.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Sandbox.version": %w`, err)} + } + } + if v, ok := su.mutation.GlobalVersion(); ok { + if err := sandbox.GlobalVersionValidator(v); err != nil { + return &ValidationError{Name: "global_version", err: fmt.Errorf(`models: validator failed for field "Sandbox.global_version": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (su *SandboxUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SandboxUpdate { + su.modifiers = append(su.modifiers, modifiers...) + return su +} + +func (su *SandboxUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := su.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(sandbox.Table, sandbox.Columns, sqlgraph.NewFieldSpec(sandbox.FieldID, field.TypeString)) + if ps := su.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := su.mutation.UpdatedAt(); ok { + _spec.SetField(sandbox.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := su.mutation.TerminatedAt(); ok { + _spec.SetField(sandbox.FieldTerminatedAt, field.TypeTime, value) + } + if value, ok := su.mutation.Deadline(); ok { + _spec.SetField(sandbox.FieldDeadline, field.TypeTime, value) + } + if value, ok := su.mutation.Status(); ok { + _spec.SetField(sandbox.FieldStatus, field.TypeEnum, value) + } + if value, ok := su.mutation.DurationMs(); ok { + _spec.SetField(sandbox.FieldDurationMs, field.TypeInt64, value) + } + if value, ok := su.mutation.AddedDurationMs(); ok { + _spec.AddField(sandbox.FieldDurationMs, field.TypeInt64, value) + } + if value, ok := su.mutation.Version(); ok { + _spec.SetField(sandbox.FieldVersion, field.TypeInt64, value) + } + if value, ok := su.mutation.AddedVersion(); ok { + _spec.AddField(sandbox.FieldVersion, field.TypeInt64, value) + } + if value, ok := su.mutation.GlobalVersion(); ok { + _spec.SetField(sandbox.FieldGlobalVersion, field.TypeInt64, value) + } + if value, ok := su.mutation.AddedGlobalVersion(); ok { + _spec.AddField(sandbox.FieldGlobalVersion, field.TypeInt64, value) + } + _spec.Node.Schema = su.schemaConfig.Sandbox + ctx = internal.NewSchemaConfigContext(ctx, su.schemaConfig) + _spec.AddModifiers(su.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, su.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{sandbox.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + su.mutation.done = true + return n, nil +} + +// SandboxUpdateOne is the builder for updating a single Sandbox entity. +type SandboxUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SandboxMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetUpdatedAt sets the "updated_at" field. +func (suo *SandboxUpdateOne) SetUpdatedAt(t time.Time) *SandboxUpdateOne { + suo.mutation.SetUpdatedAt(t) + return suo +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (suo *SandboxUpdateOne) SetNillableUpdatedAt(t *time.Time) *SandboxUpdateOne { + if t != nil { + suo.SetUpdatedAt(*t) + } + return suo +} + +// SetTerminatedAt sets the "terminated_at" field. +func (suo *SandboxUpdateOne) SetTerminatedAt(t time.Time) *SandboxUpdateOne { + suo.mutation.SetTerminatedAt(t) + return suo +} + +// SetNillableTerminatedAt sets the "terminated_at" field if the given value is not nil. +func (suo *SandboxUpdateOne) SetNillableTerminatedAt(t *time.Time) *SandboxUpdateOne { + if t != nil { + suo.SetTerminatedAt(*t) + } + return suo +} + +// SetDeadline sets the "deadline" field. +func (suo *SandboxUpdateOne) SetDeadline(t time.Time) *SandboxUpdateOne { + suo.mutation.SetDeadline(t) + return suo +} + +// SetNillableDeadline sets the "deadline" field if the given value is not nil. +func (suo *SandboxUpdateOne) SetNillableDeadline(t *time.Time) *SandboxUpdateOne { + if t != nil { + suo.SetDeadline(*t) + } + return suo +} + +// SetStatus sets the "status" field. +func (suo *SandboxUpdateOne) SetStatus(s sandbox.Status) *SandboxUpdateOne { + suo.mutation.SetStatus(s) + return suo +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (suo *SandboxUpdateOne) SetNillableStatus(s *sandbox.Status) *SandboxUpdateOne { + if s != nil { + suo.SetStatus(*s) + } + return suo +} + +// SetDurationMs sets the "duration_ms" field. +func (suo *SandboxUpdateOne) SetDurationMs(i int64) *SandboxUpdateOne { + suo.mutation.ResetDurationMs() + suo.mutation.SetDurationMs(i) + return suo +} + +// SetNillableDurationMs sets the "duration_ms" field if the given value is not nil. +func (suo *SandboxUpdateOne) SetNillableDurationMs(i *int64) *SandboxUpdateOne { + if i != nil { + suo.SetDurationMs(*i) + } + return suo +} + +// AddDurationMs adds i to the "duration_ms" field. +func (suo *SandboxUpdateOne) AddDurationMs(i int64) *SandboxUpdateOne { + suo.mutation.AddDurationMs(i) + return suo +} + +// SetVersion sets the "version" field. +func (suo *SandboxUpdateOne) SetVersion(i int64) *SandboxUpdateOne { + suo.mutation.ResetVersion() + suo.mutation.SetVersion(i) + return suo +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (suo *SandboxUpdateOne) SetNillableVersion(i *int64) *SandboxUpdateOne { + if i != nil { + suo.SetVersion(*i) + } + return suo +} + +// AddVersion adds i to the "version" field. +func (suo *SandboxUpdateOne) AddVersion(i int64) *SandboxUpdateOne { + suo.mutation.AddVersion(i) + return suo +} + +// SetGlobalVersion sets the "global_version" field. +func (suo *SandboxUpdateOne) SetGlobalVersion(i int64) *SandboxUpdateOne { + suo.mutation.ResetGlobalVersion() + suo.mutation.SetGlobalVersion(i) + return suo +} + +// SetNillableGlobalVersion sets the "global_version" field if the given value is not nil. +func (suo *SandboxUpdateOne) SetNillableGlobalVersion(i *int64) *SandboxUpdateOne { + if i != nil { + suo.SetGlobalVersion(*i) + } + return suo +} + +// AddGlobalVersion adds i to the "global_version" field. +func (suo *SandboxUpdateOne) AddGlobalVersion(i int64) *SandboxUpdateOne { + suo.mutation.AddGlobalVersion(i) + return suo +} + +// Mutation returns the SandboxMutation object of the builder. +func (suo *SandboxUpdateOne) Mutation() *SandboxMutation { + return suo.mutation +} + +// Where appends a list predicates to the SandboxUpdate builder. +func (suo *SandboxUpdateOne) Where(ps ...predicate.Sandbox) *SandboxUpdateOne { + suo.mutation.Where(ps...) + return suo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (suo *SandboxUpdateOne) Select(field string, fields ...string) *SandboxUpdateOne { + suo.fields = append([]string{field}, fields...) + return suo +} + +// Save executes the query and returns the updated Sandbox entity. +func (suo *SandboxUpdateOne) Save(ctx context.Context) (*Sandbox, error) { + return withHooks(ctx, suo.sqlSave, suo.mutation, suo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (suo *SandboxUpdateOne) SaveX(ctx context.Context) *Sandbox { + node, err := suo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (suo *SandboxUpdateOne) Exec(ctx context.Context) error { + _, err := suo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (suo *SandboxUpdateOne) ExecX(ctx context.Context) { + if err := suo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (suo *SandboxUpdateOne) check() error { + if v, ok := suo.mutation.Status(); ok { + if err := sandbox.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Sandbox.status": %w`, err)} + } + } + if v, ok := suo.mutation.DurationMs(); ok { + if err := sandbox.DurationMsValidator(v); err != nil { + return &ValidationError{Name: "duration_ms", err: fmt.Errorf(`models: validator failed for field "Sandbox.duration_ms": %w`, err)} + } + } + if v, ok := suo.mutation.Version(); ok { + if err := sandbox.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Sandbox.version": %w`, err)} + } + } + if v, ok := suo.mutation.GlobalVersion(); ok { + if err := sandbox.GlobalVersionValidator(v); err != nil { + return &ValidationError{Name: "global_version", err: fmt.Errorf(`models: validator failed for field "Sandbox.global_version": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (suo *SandboxUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SandboxUpdateOne { + suo.modifiers = append(suo.modifiers, modifiers...) + return suo +} + +func (suo *SandboxUpdateOne) sqlSave(ctx context.Context) (_node *Sandbox, err error) { + if err := suo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(sandbox.Table, sandbox.Columns, sqlgraph.NewFieldSpec(sandbox.FieldID, field.TypeString)) + id, ok := suo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Sandbox.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := suo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, sandbox.FieldID) + for _, f := range fields { + if !sandbox.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != sandbox.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := suo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := suo.mutation.UpdatedAt(); ok { + _spec.SetField(sandbox.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := suo.mutation.TerminatedAt(); ok { + _spec.SetField(sandbox.FieldTerminatedAt, field.TypeTime, value) + } + if value, ok := suo.mutation.Deadline(); ok { + _spec.SetField(sandbox.FieldDeadline, field.TypeTime, value) + } + if value, ok := suo.mutation.Status(); ok { + _spec.SetField(sandbox.FieldStatus, field.TypeEnum, value) + } + if value, ok := suo.mutation.DurationMs(); ok { + _spec.SetField(sandbox.FieldDurationMs, field.TypeInt64, value) + } + if value, ok := suo.mutation.AddedDurationMs(); ok { + _spec.AddField(sandbox.FieldDurationMs, field.TypeInt64, value) + } + if value, ok := suo.mutation.Version(); ok { + _spec.SetField(sandbox.FieldVersion, field.TypeInt64, value) + } + if value, ok := suo.mutation.AddedVersion(); ok { + _spec.AddField(sandbox.FieldVersion, field.TypeInt64, value) + } + if value, ok := suo.mutation.GlobalVersion(); ok { + _spec.SetField(sandbox.FieldGlobalVersion, field.TypeInt64, value) + } + if value, ok := suo.mutation.AddedGlobalVersion(); ok { + _spec.AddField(sandbox.FieldGlobalVersion, field.TypeInt64, value) + } + _spec.Node.Schema = suo.schemaConfig.Sandbox + ctx = internal.NewSchemaConfigContext(ctx, suo.schemaConfig) + _spec.AddModifiers(suo.modifiers...) + _node = &Sandbox{config: suo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, suo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{sandbox.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + suo.mutation.done = true + return _node, nil +} diff --git a/packages/orchestrator/internal/pkg/models/status.go b/packages/orchestrator/internal/pkg/models/status.go new file mode 100644 index 000000000..42160fb28 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/status.go @@ -0,0 +1,128 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" +) + +// Status is the model entity for the Status schema. +type Status struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Version holds the value of the "version" field. + Version int64 `json:"version,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // Status holds the value of the "status" field. + Status status.Status `json:"status,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Status) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case status.FieldID, status.FieldVersion: + values[i] = new(sql.NullInt64) + case status.FieldStatus: + values[i] = new(sql.NullString) + case status.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 Status fields. +func (s *Status) 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 status.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + s.ID = int(value.Int64) + case status.FieldVersion: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field version", values[i]) + } else if value.Valid { + s.Version = value.Int64 + } + case status.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 { + s.UpdatedAt = value.Time + } + case status.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + s.Status = status.Status(value.String) + } + default: + s.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Status. +// This includes values selected through modifiers, order, etc. +func (s *Status) Value(name string) (ent.Value, error) { + return s.selectValues.Get(name) +} + +// Update returns a builder for updating this Status. +// Note that you need to call Status.Unwrap() before calling this method if this Status +// was returned from a transaction, and the transaction was committed or rolled back. +func (s *Status) Update() *StatusUpdateOne { + return NewStatusClient(s.config).UpdateOne(s) +} + +// Unwrap unwraps the Status 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 (s *Status) Unwrap() *Status { + _tx, ok := s.config.driver.(*txDriver) + if !ok { + panic("models: Status is not a transactional entity") + } + s.config.driver = _tx.drv + return s +} + +// String implements the fmt.Stringer. +func (s *Status) String() string { + var builder strings.Builder + builder.WriteString("Status(") + builder.WriteString(fmt.Sprintf("id=%v, ", s.ID)) + builder.WriteString("version=") + builder.WriteString(fmt.Sprintf("%v", s.Version)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(s.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", s.Status)) + builder.WriteByte(')') + return builder.String() +} + +// StatusSlice is a parsable slice of Status. +type StatusSlice []*Status diff --git a/packages/orchestrator/internal/pkg/models/status/status.go b/packages/orchestrator/internal/pkg/models/status/status.go new file mode 100644 index 000000000..77f3425c8 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/status/status.go @@ -0,0 +1,101 @@ +// Code generated by ent, DO NOT EDIT. + +package status + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the status type in the database. + Label = "status" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // Table holds the table name of the status in the database. + Table = "status" +) + +// Columns holds all SQL columns for status fields. +var Columns = []string{ + FieldID, + FieldVersion, + FieldUpdatedAt, + FieldStatus, +} + +// 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 ( + // VersionValidator is a validator for the "version" field. It is called by the builders before save. + VersionValidator func(int64) error + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time +) + +// Status defines the type for the "status" enum field. +type Status string + +// StatusRunning is the default value of the Status enum. +const DefaultStatus = StatusRunning + +// Status values. +const ( + StatusInitializing Status = "initializing" + StatusRunning Status = "running" + StatusDraining Status = "draining" + StatusTerminating Status = "terminating" +) + +func (s Status) String() string { + return string(s) +} + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s Status) error { + switch s { + case StatusInitializing, StatusRunning, StatusDraining, StatusTerminating: + return nil + default: + return fmt.Errorf("status: invalid enum value for status field: %q", s) + } +} + +// OrderOption defines the ordering options for the Status 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() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} diff --git a/packages/orchestrator/internal/pkg/models/status/where.go b/packages/orchestrator/internal/pkg/models/status/where.go new file mode 100644 index 000000000..6b6895deb --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/status/where.go @@ -0,0 +1,180 @@ +// Code generated by ent, DO NOT EDIT. + +package status + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Status { + return predicate.Status(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Status { + return predicate.Status(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Status { + return predicate.Status(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Status { + return predicate.Status(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Status { + return predicate.Status(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Status { + return predicate.Status(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Status { + return predicate.Status(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Status { + return predicate.Status(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Status { + return predicate.Status(sql.FieldLTE(FieldID, id)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v int64) predicate.Status { + return predicate.Status(sql.FieldEQ(FieldVersion, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.Status { + return predicate.Status(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v int64) predicate.Status { + return predicate.Status(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v int64) predicate.Status { + return predicate.Status(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...int64) predicate.Status { + return predicate.Status(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...int64) predicate.Status { + return predicate.Status(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v int64) predicate.Status { + return predicate.Status(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v int64) predicate.Status { + return predicate.Status(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v int64) predicate.Status { + return predicate.Status(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v int64) predicate.Status { + return predicate.Status(sql.FieldLTE(FieldVersion, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Status { + return predicate.Status(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Status { + return predicate.Status(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Status { + return predicate.Status(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Status { + return predicate.Status(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Status { + return predicate.Status(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Status { + return predicate.Status(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Status { + return predicate.Status(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Status { + return predicate.Status(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v Status) predicate.Status { + return predicate.Status(sql.FieldEQ(FieldStatus, v)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v Status) predicate.Status { + return predicate.Status(sql.FieldNEQ(FieldStatus, v)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...Status) predicate.Status { + return predicate.Status(sql.FieldIn(FieldStatus, vs...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...Status) predicate.Status { + return predicate.Status(sql.FieldNotIn(FieldStatus, vs...)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Status) predicate.Status { + return predicate.Status(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Status) predicate.Status { + return predicate.Status(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Status) predicate.Status { + return predicate.Status(sql.NotPredicates(p)) +} diff --git a/packages/orchestrator/internal/pkg/models/status_create.go b/packages/orchestrator/internal/pkg/models/status_create.go new file mode 100644 index 000000000..4a95a4ec0 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/status_create.go @@ -0,0 +1,622 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" +) + +// StatusCreate is the builder for creating a Status entity. +type StatusCreate struct { + config + mutation *StatusMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetVersion sets the "version" field. +func (sc *StatusCreate) SetVersion(i int64) *StatusCreate { + sc.mutation.SetVersion(i) + return sc +} + +// SetUpdatedAt sets the "updated_at" field. +func (sc *StatusCreate) SetUpdatedAt(t time.Time) *StatusCreate { + sc.mutation.SetUpdatedAt(t) + return sc +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (sc *StatusCreate) SetNillableUpdatedAt(t *time.Time) *StatusCreate { + if t != nil { + sc.SetUpdatedAt(*t) + } + return sc +} + +// SetStatus sets the "status" field. +func (sc *StatusCreate) SetStatus(s status.Status) *StatusCreate { + sc.mutation.SetStatus(s) + return sc +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (sc *StatusCreate) SetNillableStatus(s *status.Status) *StatusCreate { + if s != nil { + sc.SetStatus(*s) + } + return sc +} + +// Mutation returns the StatusMutation object of the builder. +func (sc *StatusCreate) Mutation() *StatusMutation { + return sc.mutation +} + +// Save creates the Status in the database. +func (sc *StatusCreate) Save(ctx context.Context) (*Status, error) { + sc.defaults() + return withHooks(ctx, sc.sqlSave, sc.mutation, sc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (sc *StatusCreate) SaveX(ctx context.Context) *Status { + v, err := sc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (sc *StatusCreate) Exec(ctx context.Context) error { + _, err := sc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (sc *StatusCreate) ExecX(ctx context.Context) { + if err := sc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (sc *StatusCreate) defaults() { + if _, ok := sc.mutation.UpdatedAt(); !ok { + v := status.DefaultUpdatedAt() + sc.mutation.SetUpdatedAt(v) + } + if _, ok := sc.mutation.Status(); !ok { + v := status.DefaultStatus + sc.mutation.SetStatus(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (sc *StatusCreate) check() error { + if _, ok := sc.mutation.Version(); !ok { + return &ValidationError{Name: "version", err: errors.New(`models: missing required field "Status.version"`)} + } + if v, ok := sc.mutation.Version(); ok { + if err := status.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Status.version": %w`, err)} + } + } + if _, ok := sc.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Status.updated_at"`)} + } + if _, ok := sc.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`models: missing required field "Status.status"`)} + } + if v, ok := sc.mutation.Status(); ok { + if err := status.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Status.status": %w`, err)} + } + } + return nil +} + +func (sc *StatusCreate) sqlSave(ctx context.Context) (*Status, error) { + if err := sc.check(); err != nil { + return nil, err + } + _node, _spec := sc.createSpec() + if err := sqlgraph.CreateNode(ctx, sc.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 = int(id) + sc.mutation.id = &_node.ID + sc.mutation.done = true + return _node, nil +} + +func (sc *StatusCreate) createSpec() (*Status, *sqlgraph.CreateSpec) { + var ( + _node = &Status{config: sc.config} + _spec = sqlgraph.NewCreateSpec(status.Table, sqlgraph.NewFieldSpec(status.FieldID, field.TypeInt)) + ) + _spec.Schema = sc.schemaConfig.Status + _spec.OnConflict = sc.conflict + if value, ok := sc.mutation.Version(); ok { + _spec.SetField(status.FieldVersion, field.TypeInt64, value) + _node.Version = value + } + if value, ok := sc.mutation.UpdatedAt(); ok { + _spec.SetField(status.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := sc.mutation.Status(); ok { + _spec.SetField(status.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Status.Create(). +// SetVersion(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.StatusUpsert) { +// SetVersion(v+v). +// }). +// Exec(ctx) +func (sc *StatusCreate) OnConflict(opts ...sql.ConflictOption) *StatusUpsertOne { + sc.conflict = opts + return &StatusUpsertOne{ + create: sc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Status.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (sc *StatusCreate) OnConflictColumns(columns ...string) *StatusUpsertOne { + sc.conflict = append(sc.conflict, sql.ConflictColumns(columns...)) + return &StatusUpsertOne{ + create: sc, + } +} + +type ( + // StatusUpsertOne is the builder for "upsert"-ing + // one Status node. + StatusUpsertOne struct { + create *StatusCreate + } + + // StatusUpsert is the "OnConflict" setter. + StatusUpsert struct { + *sql.UpdateSet + } +) + +// SetVersion sets the "version" field. +func (u *StatusUpsert) SetVersion(v int64) *StatusUpsert { + u.Set(status.FieldVersion, v) + return u +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *StatusUpsert) UpdateVersion() *StatusUpsert { + u.SetExcluded(status.FieldVersion) + return u +} + +// AddVersion adds v to the "version" field. +func (u *StatusUpsert) AddVersion(v int64) *StatusUpsert { + u.Add(status.FieldVersion, v) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *StatusUpsert) SetUpdatedAt(v time.Time) *StatusUpsert { + u.Set(status.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *StatusUpsert) UpdateUpdatedAt() *StatusUpsert { + u.SetExcluded(status.FieldUpdatedAt) + return u +} + +// SetStatus sets the "status" field. +func (u *StatusUpsert) SetStatus(v status.Status) *StatusUpsert { + u.Set(status.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *StatusUpsert) UpdateStatus() *StatusUpsert { + u.SetExcluded(status.FieldStatus) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.Status.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *StatusUpsertOne) UpdateNewValues() *StatusUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Status.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *StatusUpsertOne) Ignore() *StatusUpsertOne { + 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 *StatusUpsertOne) DoNothing() *StatusUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the StatusCreate.OnConflict +// documentation for more info. +func (u *StatusUpsertOne) Update(set func(*StatusUpsert)) *StatusUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&StatusUpsert{UpdateSet: update}) + })) + return u +} + +// SetVersion sets the "version" field. +func (u *StatusUpsertOne) SetVersion(v int64) *StatusUpsertOne { + return u.Update(func(s *StatusUpsert) { + s.SetVersion(v) + }) +} + +// AddVersion adds v to the "version" field. +func (u *StatusUpsertOne) AddVersion(v int64) *StatusUpsertOne { + return u.Update(func(s *StatusUpsert) { + s.AddVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *StatusUpsertOne) UpdateVersion() *StatusUpsertOne { + return u.Update(func(s *StatusUpsert) { + s.UpdateVersion() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *StatusUpsertOne) SetUpdatedAt(v time.Time) *StatusUpsertOne { + return u.Update(func(s *StatusUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *StatusUpsertOne) UpdateUpdatedAt() *StatusUpsertOne { + return u.Update(func(s *StatusUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetStatus sets the "status" field. +func (u *StatusUpsertOne) SetStatus(v status.Status) *StatusUpsertOne { + return u.Update(func(s *StatusUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *StatusUpsertOne) UpdateStatus() *StatusUpsertOne { + return u.Update(func(s *StatusUpsert) { + s.UpdateStatus() + }) +} + +// Exec executes the query. +func (u *StatusUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("models: missing options for StatusCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *StatusUpsertOne) 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 *StatusUpsertOne) ID(ctx context.Context) (id int, 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 *StatusUpsertOne) IDX(ctx context.Context) int { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// StatusCreateBulk is the builder for creating many Status entities in bulk. +type StatusCreateBulk struct { + config + err error + builders []*StatusCreate + conflict []sql.ConflictOption +} + +// Save creates the Status entities in the database. +func (scb *StatusCreateBulk) Save(ctx context.Context) ([]*Status, error) { + if scb.err != nil { + return nil, scb.err + } + specs := make([]*sqlgraph.CreateSpec, len(scb.builders)) + nodes := make([]*Status, len(scb.builders)) + mutators := make([]Mutator, len(scb.builders)) + for i := range scb.builders { + func(i int, root context.Context) { + builder := scb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*StatusMutation) + 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, scb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = scb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, scb.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 = int(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, scb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (scb *StatusCreateBulk) SaveX(ctx context.Context) []*Status { + v, err := scb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (scb *StatusCreateBulk) Exec(ctx context.Context) error { + _, err := scb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (scb *StatusCreateBulk) ExecX(ctx context.Context) { + if err := scb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Status.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.StatusUpsert) { +// SetVersion(v+v). +// }). +// Exec(ctx) +func (scb *StatusCreateBulk) OnConflict(opts ...sql.ConflictOption) *StatusUpsertBulk { + scb.conflict = opts + return &StatusUpsertBulk{ + create: scb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Status.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (scb *StatusCreateBulk) OnConflictColumns(columns ...string) *StatusUpsertBulk { + scb.conflict = append(scb.conflict, sql.ConflictColumns(columns...)) + return &StatusUpsertBulk{ + create: scb, + } +} + +// StatusUpsertBulk is the builder for "upsert"-ing +// a bulk of Status nodes. +type StatusUpsertBulk struct { + create *StatusCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Status.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *StatusUpsertBulk) UpdateNewValues() *StatusUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Status.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *StatusUpsertBulk) Ignore() *StatusUpsertBulk { + 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 *StatusUpsertBulk) DoNothing() *StatusUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the StatusCreateBulk.OnConflict +// documentation for more info. +func (u *StatusUpsertBulk) Update(set func(*StatusUpsert)) *StatusUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&StatusUpsert{UpdateSet: update}) + })) + return u +} + +// SetVersion sets the "version" field. +func (u *StatusUpsertBulk) SetVersion(v int64) *StatusUpsertBulk { + return u.Update(func(s *StatusUpsert) { + s.SetVersion(v) + }) +} + +// AddVersion adds v to the "version" field. +func (u *StatusUpsertBulk) AddVersion(v int64) *StatusUpsertBulk { + return u.Update(func(s *StatusUpsert) { + s.AddVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *StatusUpsertBulk) UpdateVersion() *StatusUpsertBulk { + return u.Update(func(s *StatusUpsert) { + s.UpdateVersion() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *StatusUpsertBulk) SetUpdatedAt(v time.Time) *StatusUpsertBulk { + return u.Update(func(s *StatusUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *StatusUpsertBulk) UpdateUpdatedAt() *StatusUpsertBulk { + return u.Update(func(s *StatusUpsert) { + s.UpdateUpdatedAt() + }) +} + +// SetStatus sets the "status" field. +func (u *StatusUpsertBulk) SetStatus(v status.Status) *StatusUpsertBulk { + return u.Update(func(s *StatusUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *StatusUpsertBulk) UpdateStatus() *StatusUpsertBulk { + return u.Update(func(s *StatusUpsert) { + s.UpdateStatus() + }) +} + +// Exec executes the query. +func (u *StatusUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("models: OnConflict was set for builder %d. Set it on the StatusCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("models: missing options for StatusCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *StatusUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/packages/orchestrator/internal/pkg/models/status_delete.go b/packages/orchestrator/internal/pkg/models/status_delete.go new file mode 100644 index 000000000..cfea8babb --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/status_delete.go @@ -0,0 +1,91 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" +) + +// StatusDelete is the builder for deleting a Status entity. +type StatusDelete struct { + config + hooks []Hook + mutation *StatusMutation +} + +// Where appends a list predicates to the StatusDelete builder. +func (sd *StatusDelete) Where(ps ...predicate.Status) *StatusDelete { + sd.mutation.Where(ps...) + return sd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (sd *StatusDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, sd.sqlExec, sd.mutation, sd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (sd *StatusDelete) ExecX(ctx context.Context) int { + n, err := sd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (sd *StatusDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(status.Table, sqlgraph.NewFieldSpec(status.FieldID, field.TypeInt)) + _spec.Node.Schema = sd.schemaConfig.Status + ctx = internal.NewSchemaConfigContext(ctx, sd.schemaConfig) + if ps := sd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, sd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + sd.mutation.done = true + return affected, err +} + +// StatusDeleteOne is the builder for deleting a single Status entity. +type StatusDeleteOne struct { + sd *StatusDelete +} + +// Where appends a list predicates to the StatusDelete builder. +func (sdo *StatusDeleteOne) Where(ps ...predicate.Status) *StatusDeleteOne { + sdo.sd.mutation.Where(ps...) + return sdo +} + +// Exec executes the deletion query. +func (sdo *StatusDeleteOne) Exec(ctx context.Context) error { + n, err := sdo.sd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{status.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (sdo *StatusDeleteOne) ExecX(ctx context.Context) { + if err := sdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/packages/orchestrator/internal/pkg/models/status_query.go b/packages/orchestrator/internal/pkg/models/status_query.go new file mode 100644 index 000000000..d4c0b59c0 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/status_query.go @@ -0,0 +1,556 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" +) + +// StatusQuery is the builder for querying Status entities. +type StatusQuery struct { + config + ctx *QueryContext + order []status.OrderOption + inters []Interceptor + predicates []predicate.Status + 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 StatusQuery builder. +func (sq *StatusQuery) Where(ps ...predicate.Status) *StatusQuery { + sq.predicates = append(sq.predicates, ps...) + return sq +} + +// Limit the number of records to be returned by this query. +func (sq *StatusQuery) Limit(limit int) *StatusQuery { + sq.ctx.Limit = &limit + return sq +} + +// Offset to start from. +func (sq *StatusQuery) Offset(offset int) *StatusQuery { + sq.ctx.Offset = &offset + return sq +} + +// 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 (sq *StatusQuery) Unique(unique bool) *StatusQuery { + sq.ctx.Unique = &unique + return sq +} + +// Order specifies how the records should be ordered. +func (sq *StatusQuery) Order(o ...status.OrderOption) *StatusQuery { + sq.order = append(sq.order, o...) + return sq +} + +// First returns the first Status entity from the query. +// Returns a *NotFoundError when no Status was found. +func (sq *StatusQuery) First(ctx context.Context) (*Status, error) { + nodes, err := sq.Limit(1).All(setContextOp(ctx, sq.ctx, "First")) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{status.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (sq *StatusQuery) FirstX(ctx context.Context) *Status { + node, err := sq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Status ID from the query. +// Returns a *NotFoundError when no Status ID was found. +func (sq *StatusQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = sq.Limit(1).IDs(setContextOp(ctx, sq.ctx, "FirstID")); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{status.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (sq *StatusQuery) FirstIDX(ctx context.Context) int { + id, err := sq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Status entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Status entity is found. +// Returns a *NotFoundError when no Status entities are found. +func (sq *StatusQuery) Only(ctx context.Context) (*Status, error) { + nodes, err := sq.Limit(2).All(setContextOp(ctx, sq.ctx, "Only")) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{status.Label} + default: + return nil, &NotSingularError{status.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (sq *StatusQuery) OnlyX(ctx context.Context) *Status { + node, err := sq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Status ID in the query. +// Returns a *NotSingularError when more than one Status ID is found. +// Returns a *NotFoundError when no entities are found. +func (sq *StatusQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = sq.Limit(2).IDs(setContextOp(ctx, sq.ctx, "OnlyID")); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{status.Label} + default: + err = &NotSingularError{status.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (sq *StatusQuery) OnlyIDX(ctx context.Context) int { + id, err := sq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of StatusSlice. +func (sq *StatusQuery) All(ctx context.Context) ([]*Status, error) { + ctx = setContextOp(ctx, sq.ctx, "All") + if err := sq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Status, *StatusQuery]() + return withInterceptors[[]*Status](ctx, sq, qr, sq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (sq *StatusQuery) AllX(ctx context.Context) []*Status { + nodes, err := sq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Status IDs. +func (sq *StatusQuery) IDs(ctx context.Context) (ids []int, err error) { + if sq.ctx.Unique == nil && sq.path != nil { + sq.Unique(true) + } + ctx = setContextOp(ctx, sq.ctx, "IDs") + if err = sq.Select(status.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (sq *StatusQuery) IDsX(ctx context.Context) []int { + ids, err := sq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (sq *StatusQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, sq.ctx, "Count") + if err := sq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, sq, querierCount[*StatusQuery](), sq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (sq *StatusQuery) CountX(ctx context.Context) int { + count, err := sq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (sq *StatusQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, sq.ctx, "Exist") + switch _, err := sq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (sq *StatusQuery) ExistX(ctx context.Context) bool { + exist, err := sq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the StatusQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (sq *StatusQuery) Clone() *StatusQuery { + if sq == nil { + return nil + } + return &StatusQuery{ + config: sq.config, + ctx: sq.ctx.Clone(), + order: append([]status.OrderOption{}, sq.order...), + inters: append([]Interceptor{}, sq.inters...), + predicates: append([]predicate.Status{}, sq.predicates...), + // clone intermediate query. + sql: sq.sql.Clone(), + path: sq.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 { +// Version int64 `json:"version,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Status.Query(). +// GroupBy(status.FieldVersion). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (sq *StatusQuery) GroupBy(field string, fields ...string) *StatusGroupBy { + sq.ctx.Fields = append([]string{field}, fields...) + grbuild := &StatusGroupBy{build: sq} + grbuild.flds = &sq.ctx.Fields + grbuild.label = status.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 { +// Version int64 `json:"version,omitempty"` +// } +// +// client.Status.Query(). +// Select(status.FieldVersion). +// Scan(ctx, &v) +func (sq *StatusQuery) Select(fields ...string) *StatusSelect { + sq.ctx.Fields = append(sq.ctx.Fields, fields...) + sbuild := &StatusSelect{StatusQuery: sq} + sbuild.label = status.Label + sbuild.flds, sbuild.scan = &sq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a StatusSelect configured with the given aggregations. +func (sq *StatusQuery) Aggregate(fns ...AggregateFunc) *StatusSelect { + return sq.Select().Aggregate(fns...) +} + +func (sq *StatusQuery) prepareQuery(ctx context.Context) error { + for _, inter := range sq.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, sq); err != nil { + return err + } + } + } + for _, f := range sq.ctx.Fields { + if !status.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if sq.path != nil { + prev, err := sq.path(ctx) + if err != nil { + return err + } + sq.sql = prev + } + return nil +} + +func (sq *StatusQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Status, error) { + var ( + nodes = []*Status{} + _spec = sq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Status).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Status{config: sq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + _spec.Node.Schema = sq.schemaConfig.Status + ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) + if len(sq.modifiers) > 0 { + _spec.Modifiers = sq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, sq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (sq *StatusQuery) sqlCount(ctx context.Context) (int, error) { + _spec := sq.querySpec() + _spec.Node.Schema = sq.schemaConfig.Status + ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) + if len(sq.modifiers) > 0 { + _spec.Modifiers = sq.modifiers + } + _spec.Node.Columns = sq.ctx.Fields + if len(sq.ctx.Fields) > 0 { + _spec.Unique = sq.ctx.Unique != nil && *sq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, sq.driver, _spec) +} + +func (sq *StatusQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(status.Table, status.Columns, sqlgraph.NewFieldSpec(status.FieldID, field.TypeInt)) + _spec.From = sq.sql + if unique := sq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if sq.path != nil { + _spec.Unique = true + } + if fields := sq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, status.FieldID) + for i := range fields { + if fields[i] != status.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := sq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := sq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := sq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := sq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (sq *StatusQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(sq.driver.Dialect()) + t1 := builder.Table(status.Table) + columns := sq.ctx.Fields + if len(columns) == 0 { + columns = status.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if sq.sql != nil { + selector = sq.sql + selector.Select(selector.Columns(columns...)...) + } + if sq.ctx.Unique != nil && *sq.ctx.Unique { + selector.Distinct() + } + t1.Schema(sq.schemaConfig.Status) + ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) + selector.WithContext(ctx) + for _, m := range sq.modifiers { + m(selector) + } + for _, p := range sq.predicates { + p(selector) + } + for _, p := range sq.order { + p(selector) + } + if offset := sq.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 := sq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (sq *StatusQuery) Modify(modifiers ...func(s *sql.Selector)) *StatusSelect { + sq.modifiers = append(sq.modifiers, modifiers...) + return sq.Select() +} + +// StatusGroupBy is the group-by builder for Status entities. +type StatusGroupBy struct { + selector + build *StatusQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (sgb *StatusGroupBy) Aggregate(fns ...AggregateFunc) *StatusGroupBy { + sgb.fns = append(sgb.fns, fns...) + return sgb +} + +// Scan applies the selector query and scans the result into the given value. +func (sgb *StatusGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, sgb.build.ctx, "GroupBy") + if err := sgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*StatusQuery, *StatusGroupBy](ctx, sgb.build, sgb, sgb.build.inters, v) +} + +func (sgb *StatusGroupBy) sqlScan(ctx context.Context, root *StatusQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(sgb.fns)) + for _, fn := range sgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*sgb.flds)+len(sgb.fns)) + for _, f := range *sgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*sgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := sgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// StatusSelect is the builder for selecting fields of Status entities. +type StatusSelect struct { + *StatusQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ss *StatusSelect) Aggregate(fns ...AggregateFunc) *StatusSelect { + ss.fns = append(ss.fns, fns...) + return ss +} + +// Scan applies the selector query and scans the result into the given value. +func (ss *StatusSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ss.ctx, "Select") + if err := ss.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*StatusQuery, *StatusSelect](ctx, ss.StatusQuery, ss, ss.inters, v) +} + +func (ss *StatusSelect) sqlScan(ctx context.Context, root *StatusQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ss.fns)) + for _, fn := range ss.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ss.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 := ss.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (ss *StatusSelect) Modify(modifiers ...func(s *sql.Selector)) *StatusSelect { + ss.modifiers = append(ss.modifiers, modifiers...) + return ss +} diff --git a/packages/orchestrator/internal/pkg/models/status_update.go b/packages/orchestrator/internal/pkg/models/status_update.go new file mode 100644 index 000000000..a53bf6cf5 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/status_update.go @@ -0,0 +1,355 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" +) + +// StatusUpdate is the builder for updating Status entities. +type StatusUpdate struct { + config + hooks []Hook + mutation *StatusMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the StatusUpdate builder. +func (su *StatusUpdate) Where(ps ...predicate.Status) *StatusUpdate { + su.mutation.Where(ps...) + return su +} + +// SetVersion sets the "version" field. +func (su *StatusUpdate) SetVersion(i int64) *StatusUpdate { + su.mutation.ResetVersion() + su.mutation.SetVersion(i) + return su +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (su *StatusUpdate) SetNillableVersion(i *int64) *StatusUpdate { + if i != nil { + su.SetVersion(*i) + } + return su +} + +// AddVersion adds i to the "version" field. +func (su *StatusUpdate) AddVersion(i int64) *StatusUpdate { + su.mutation.AddVersion(i) + return su +} + +// SetUpdatedAt sets the "updated_at" field. +func (su *StatusUpdate) SetUpdatedAt(t time.Time) *StatusUpdate { + su.mutation.SetUpdatedAt(t) + return su +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (su *StatusUpdate) SetNillableUpdatedAt(t *time.Time) *StatusUpdate { + if t != nil { + su.SetUpdatedAt(*t) + } + return su +} + +// SetStatus sets the "status" field. +func (su *StatusUpdate) SetStatus(s status.Status) *StatusUpdate { + su.mutation.SetStatus(s) + return su +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (su *StatusUpdate) SetNillableStatus(s *status.Status) *StatusUpdate { + if s != nil { + su.SetStatus(*s) + } + return su +} + +// Mutation returns the StatusMutation object of the builder. +func (su *StatusUpdate) Mutation() *StatusMutation { + return su.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (su *StatusUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, su.sqlSave, su.mutation, su.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (su *StatusUpdate) SaveX(ctx context.Context) int { + affected, err := su.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (su *StatusUpdate) Exec(ctx context.Context) error { + _, err := su.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (su *StatusUpdate) ExecX(ctx context.Context) { + if err := su.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (su *StatusUpdate) check() error { + if v, ok := su.mutation.Version(); ok { + if err := status.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Status.version": %w`, err)} + } + } + if v, ok := su.mutation.Status(); ok { + if err := status.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Status.status": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (su *StatusUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *StatusUpdate { + su.modifiers = append(su.modifiers, modifiers...) + return su +} + +func (su *StatusUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := su.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(status.Table, status.Columns, sqlgraph.NewFieldSpec(status.FieldID, field.TypeInt)) + if ps := su.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := su.mutation.Version(); ok { + _spec.SetField(status.FieldVersion, field.TypeInt64, value) + } + if value, ok := su.mutation.AddedVersion(); ok { + _spec.AddField(status.FieldVersion, field.TypeInt64, value) + } + if value, ok := su.mutation.UpdatedAt(); ok { + _spec.SetField(status.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := su.mutation.Status(); ok { + _spec.SetField(status.FieldStatus, field.TypeEnum, value) + } + _spec.Node.Schema = su.schemaConfig.Status + ctx = internal.NewSchemaConfigContext(ctx, su.schemaConfig) + _spec.AddModifiers(su.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, su.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{status.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + su.mutation.done = true + return n, nil +} + +// StatusUpdateOne is the builder for updating a single Status entity. +type StatusUpdateOne struct { + config + fields []string + hooks []Hook + mutation *StatusMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetVersion sets the "version" field. +func (suo *StatusUpdateOne) SetVersion(i int64) *StatusUpdateOne { + suo.mutation.ResetVersion() + suo.mutation.SetVersion(i) + return suo +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (suo *StatusUpdateOne) SetNillableVersion(i *int64) *StatusUpdateOne { + if i != nil { + suo.SetVersion(*i) + } + return suo +} + +// AddVersion adds i to the "version" field. +func (suo *StatusUpdateOne) AddVersion(i int64) *StatusUpdateOne { + suo.mutation.AddVersion(i) + return suo +} + +// SetUpdatedAt sets the "updated_at" field. +func (suo *StatusUpdateOne) SetUpdatedAt(t time.Time) *StatusUpdateOne { + suo.mutation.SetUpdatedAt(t) + return suo +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (suo *StatusUpdateOne) SetNillableUpdatedAt(t *time.Time) *StatusUpdateOne { + if t != nil { + suo.SetUpdatedAt(*t) + } + return suo +} + +// SetStatus sets the "status" field. +func (suo *StatusUpdateOne) SetStatus(s status.Status) *StatusUpdateOne { + suo.mutation.SetStatus(s) + return suo +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (suo *StatusUpdateOne) SetNillableStatus(s *status.Status) *StatusUpdateOne { + if s != nil { + suo.SetStatus(*s) + } + return suo +} + +// Mutation returns the StatusMutation object of the builder. +func (suo *StatusUpdateOne) Mutation() *StatusMutation { + return suo.mutation +} + +// Where appends a list predicates to the StatusUpdate builder. +func (suo *StatusUpdateOne) Where(ps ...predicate.Status) *StatusUpdateOne { + suo.mutation.Where(ps...) + return suo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (suo *StatusUpdateOne) Select(field string, fields ...string) *StatusUpdateOne { + suo.fields = append([]string{field}, fields...) + return suo +} + +// Save executes the query and returns the updated Status entity. +func (suo *StatusUpdateOne) Save(ctx context.Context) (*Status, error) { + return withHooks(ctx, suo.sqlSave, suo.mutation, suo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (suo *StatusUpdateOne) SaveX(ctx context.Context) *Status { + node, err := suo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (suo *StatusUpdateOne) Exec(ctx context.Context) error { + _, err := suo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (suo *StatusUpdateOne) ExecX(ctx context.Context) { + if err := suo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (suo *StatusUpdateOne) check() error { + if v, ok := suo.mutation.Version(); ok { + if err := status.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Status.version": %w`, err)} + } + } + if v, ok := suo.mutation.Status(); ok { + if err := status.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Status.status": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (suo *StatusUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *StatusUpdateOne { + suo.modifiers = append(suo.modifiers, modifiers...) + return suo +} + +func (suo *StatusUpdateOne) sqlSave(ctx context.Context) (_node *Status, err error) { + if err := suo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(status.Table, status.Columns, sqlgraph.NewFieldSpec(status.FieldID, field.TypeInt)) + id, ok := suo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Status.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := suo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, status.FieldID) + for _, f := range fields { + if !status.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != status.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := suo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := suo.mutation.Version(); ok { + _spec.SetField(status.FieldVersion, field.TypeInt64, value) + } + if value, ok := suo.mutation.AddedVersion(); ok { + _spec.AddField(status.FieldVersion, field.TypeInt64, value) + } + if value, ok := suo.mutation.UpdatedAt(); ok { + _spec.SetField(status.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := suo.mutation.Status(); ok { + _spec.SetField(status.FieldStatus, field.TypeEnum, value) + } + _spec.Node.Schema = suo.schemaConfig.Status + ctx = internal.NewSchemaConfigContext(ctx, suo.schemaConfig) + _spec.AddModifiers(suo.modifiers...) + _node = &Status{config: suo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, suo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{status.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + suo.mutation.done = true + return _node, nil +} diff --git a/packages/orchestrator/internal/pkg/models/tx.go b/packages/orchestrator/internal/pkg/models/tx.go new file mode 100644 index 000000000..8e1937981 --- /dev/null +++ b/packages/orchestrator/internal/pkg/models/tx.go @@ -0,0 +1,213 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Sandbox is the client for interacting with the Sandbox builders. + Sandbox *SandboxClient + // Status is the client for interacting with the Status builders. + Status *StatusClient + + // lazily loaded. + client *Client + clientOnce sync.Once + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.Sandbox = NewSandboxClient(tx.config) + tx.Status = NewStatusClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: Sandbox.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/packages/orchestrator/internal/pkg/schema/sandbox.go b/packages/orchestrator/internal/pkg/schema/sandbox.go new file mode 100644 index 000000000..6d4721447 --- /dev/null +++ b/packages/orchestrator/internal/pkg/schema/sandbox.go @@ -0,0 +1,32 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema/field" +) + +type Sandbox struct { + ent.Schema +} + +func (Sandbox) Fields() []ent.Field { + return []ent.Field{ + field.String("id").Unique().Immutable().NotEmpty(), + field.Time("started_at").Immutable().Default(time.Now). + Annotations( + entsql.Default("CURRENT_TIMESTAMP"), + ), + field.Time("updated_at").Default(time.Now), + field.Time("terminated_at").Nillable(), + field.Time("deadline").Nillable(), + field.Enum("status").Values("pending", "running", "paused", "terminated").Default("pending"), + field.Int64("duration_ms").NonNegative(), + field.Int64("version").NonNegative().Comment("an incrementing clock of this "), + field.Int64("global_version").NonNegative().Comment("a record of the version of the global state of the last modification."), + // TODO: should we store more data persistently about sandboxes? + // TODO: mechanism to cleanup + } +} diff --git a/packages/orchestrator/internal/pkg/schema/status.go b/packages/orchestrator/internal/pkg/schema/status.go new file mode 100644 index 000000000..ca28ec432 --- /dev/null +++ b/packages/orchestrator/internal/pkg/schema/status.go @@ -0,0 +1,22 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/field" +) + +// The Status table stores the global status of the +// orchestrator. Exists to have a global version/clock +type Status struct { + ent.Schema +} + +func (Status) Fields() []ent.Field { + return []ent.Field{ + field.Int64("version").NonNegative().Unique(), + field.Time("updated_at").Default(time.Now), + field.Enum("status").Values("initializing", "running", "draining", "terminating").Default("running"), + } +} diff --git a/packages/orchestrator/internal/sandbox/checks.go b/packages/orchestrator/internal/sandbox/checks.go index 31aa7f1f6..d42466957 100644 --- a/packages/orchestrator/internal/sandbox/checks.go +++ b/packages/orchestrator/internal/sandbox/checks.go @@ -80,7 +80,9 @@ func (s *Sandbox) Healthcheck(ctx context.Context, alwaysReport bool) { address := fmt.Sprintf("http://%s:%d/health", s.Slot.HostIP(), consts.DefaultEnvdServerPort) - request, err := http.NewRequestWithContext(ctx, "GET", address, nil) + var request *http.Request + + request, err = http.NewRequestWithContext(ctx, "GET", address, nil) if err != nil { return } diff --git a/packages/orchestrator/internal/server/main.go b/packages/orchestrator/internal/server/main.go index 5a13abf8a..af9bc0f5d 100644 --- a/packages/orchestrator/internal/server/main.go +++ b/packages/orchestrator/internal/server/main.go @@ -7,6 +7,7 @@ import ( "math" "net" "sync" + "sync/atomic" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery" @@ -19,7 +20,11 @@ import ( "google.golang.org/grpc/health" "google.golang.org/grpc/health/grpc_health_v1" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "github.com/e2b-dev/infra/packages/orchestrator/internal/db" "github.com/e2b-dev/infra/packages/orchestrator/internal/dns" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/network" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/template" @@ -35,6 +40,7 @@ type server struct { orchestrator.UnimplementedSandboxServiceServer sandboxes *smap.Map[*sandbox.Sandbox] dns *dns.DNS + db *db.DB tracer trace.Tracer networkPool *network.Pool templateCache *template.Cache @@ -47,6 +53,8 @@ type Service struct { grpc *grpc.Server dns *dns.DNS port uint16 + db *models.Client + started atomic.Bool shutdown struct { once sync.Once op func(context.Context) error @@ -106,6 +114,17 @@ func New(ctx context.Context, port uint) (*Service, error) { } } + // BLOCK: setup database + { + const dbConnStr = "file:./db/sandboxes.db?_journal_mode=wal" + drv, err := sql.Open(dialect.SQLite, dbConnStr) + if err != nil { + return nil, fmt.Errorf("connecting to %q: %w", dbConnStr, err) + } + + srv.db = models.NewClient(models.Driver(drv)) + } + orchestrator.RegisterSandboxServiceServer(srv.grpc, srv.server) grpc_health_v1.RegisterHealthServer(srv.grpc, health.NewServer()) @@ -118,7 +137,18 @@ func (srv *Service) Start(context.Context) error { return errors.New("orchestrator services are not initialized") } + if !srv.started.CompareAndSwap(false, true) { + return errors.New("cannot start the orchestrator service more than once") + } + + zap.L().Info("starting orchestrator service") + + wg := sync.WaitGroup{} + wg.Add(1) go func() { + defer zap.L().Info("DNS server returned") + defer wg.Done() + zap.L().Info("Starting DNS server") if err := srv.dns.Start("127.0.0.4", 53); err != nil { zap.L().Fatal("Failed running DNS server", zap.Error(err)) @@ -131,15 +161,21 @@ func (srv *Service) Start(context.Context) error { return fmt.Errorf("failed to listen on port %d: %w", srv.port, err) } - zap.L().Info("Starting orchestrator server", zap.Uint16("port", srv.port)) - + wg.Add(1) go func() { + defer zap.L().Info("gRPC service returned") + defer wg.Done() + + zap.L().Info("starting orchestrator server", zap.Uint16("port", srv.port)) + if err := srv.grpc.Serve(lis); err != nil { zap.L().Fatal("grpc server failed to serve", zap.Error(err)) } }() srv.shutdown.op = func(ctx context.Context) error { + defer zap.L().Info("orchestrator service has completed shutdown") + var errs []error srv.grpc.GracefulStop() @@ -148,6 +184,12 @@ func (srv *Service) Start(context.Context) error { errs = append(errs, err) } + wg.Wait() + + if err := srv.db.Close(); err != nil { + errs = append(errs, err) + } + if err := srv.dns.Close(ctx); err != nil { errs = append(errs, err) } diff --git a/packages/orchestrator/internal/server/sandboxes.go b/packages/orchestrator/internal/server/sandboxes.go index 0a4d8e0eb..aa73f2114 100644 --- a/packages/orchestrator/internal/server/sandboxes.go +++ b/packages/orchestrator/internal/server/sandboxes.go @@ -12,17 +12,19 @@ import ( "go.uber.org/zap" "golang.org/x/sync/semaphore" "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/timestamppb" "github.com/e2b-dev/infra/packages/orchestrator/internal/consul" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" + dbsandbox "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/build" "github.com/e2b-dev/infra/packages/shared/pkg/grpc/orchestrator" sbxlogger "github.com/e2b-dev/infra/packages/shared/pkg/logger/sandbox" "github.com/e2b-dev/infra/packages/shared/pkg/storage" "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" + "github.com/gogo/status" ) const ( @@ -66,25 +68,38 @@ func (s *server) Create(ctxConn context.Context, req *orchestrator.SandboxCreate errMsg := fmt.Errorf("failed to cleanup sandbox: %w", errors.Join(err, context.Cause(ctx), cleanupErr)) telemetry.ReportCriticalError(ctx, errMsg) - return nil, status.New(codes.Internal, errMsg.Error()).Err() + return nil, status.New(codes.Internal, err.Error()).Err() } + started := time.Now() s.sandboxes.Insert(req.Sandbox.SandboxId, sbx) + s.db.CreateSandbox(ctx, func(sc *models.SandboxCreate) { + sc.SetID(req.Sandbox.SandboxId) + sc.SetStatus(dbsandbox.Status(dbsandbox.StatusRunning)) + sc.SetStartedAt(started) + sc.SetDeadline(req.EndTime.AsTime()) + }) go func() { - waitErr := sbx.Wait() - if waitErr != nil { - sbxlogger.I(sbx).Error("failed to wait for sandbox, cleaning up", zap.Error(waitErr)) + if err := sbx.Wait(); err != nil { + sbxlogger.I(sbx).Error("failed to wait for sandbox, cleaning up", zap.Error(err)) } + ended := time.Now() - cleanupErr := cleanup.Run() - if cleanupErr != nil { - sbxlogger.I(sbx).Error("failed to cleanup sandbox, will remove from cache", zap.Error(cleanupErr)) + if err := cleanup.Run(); err != nil { + sbxlogger.I(sbx).Error("failed to cleanup sandbox, will remove from cache", zap.Error(err)) } s.sandboxes.Remove(req.Sandbox.SandboxId) + if err := s.db.UpdateSandbox(ctx, req.Sandbox.SandboxId, func(sbu *models.SandboxUpdateOne) { + sbu.SetStatus(dbsandbox.StatusTerminated). + SetTerminatedAt(time.Now().Round(time.Millisecond)). + SetDurationMs(ended.Sub(started).Milliseconds()) + }); err != nil { + sbxlogger.E(sbx).Info("failed to cleanup db record for sandbox", zap.Error(err)) + } - sbxlogger.E(sbx).Info("Sandbox killed") + sbxlogger.E(sbx).Info("sandbox killed") }() return &orchestrator.SandboxCreateResponse{ @@ -111,6 +126,12 @@ func (s *server) Update(ctx context.Context, req *orchestrator.SandboxUpdateRequ item.EndAt = req.EndTime.AsTime() + if err := s.db.UpdateSandbox(ctx, req.SandboxId, func(sbu *models.SandboxUpdateOne) { + sbu.SetDeadline(item.EndAt) + }); err != nil { + return nil, status.New(codes.Internal, fmt.Sprintf("db update sandbox: %w", err)).Err() + } + return &emptypb.Empty{}, nil } @@ -180,6 +201,12 @@ func (s *server) Delete(ctxConn context.Context, in *orchestrator.SandboxDeleteR sbx.Healthcheck(loggingCtx, true) sbx.LogMetrics(loggingCtx) + if err := s.db.UpdateSandbox(ctx, in.SandboxId, func(sbu *models.SandboxUpdateOne) { + sbu.SetTerminatedAt(time.Now()).SetStatus(dbsandbox.StatusTerminated) + }); err != nil { + fmt.Fprintf(os.Stderr, "error setting sandbox deleted '%s': %v\n", in.SandboxId, err) + } + err := sbx.Stop() if err != nil { sbxlogger.I(sbx).Error("error stopping sandbox", zap.String("sandbox_id", in.SandboxId), zap.Error(err)) @@ -208,7 +235,6 @@ func (s *server) Pause(ctx context.Context, in *orchestrator.SandboxPauseRequest defer releaseOnce() s.pauseMu.Lock() - sbx, ok := s.sandboxes.Get(in.SandboxId) if !ok { s.pauseMu.Unlock() @@ -222,6 +248,13 @@ func (s *server) Pause(ctx context.Context, in *orchestrator.SandboxPauseRequest s.dns.Remove(in.SandboxId, sbx.Slot.HostIP()) s.sandboxes.Remove(in.SandboxId) + if err := s.db.UpdateSandbox(ctx, in.SandboxId, func(sbu *models.SandboxUpdateOne) { + // TODO: either stop accounting for duration or update duration in the wrapper. + sbu.SetDurationMs(time.Now().Sub(sbx.StartedAt).Milliseconds()).SetStatus(dbsandbox.StatusPaused) + }); err != nil { + fmt.Fprintf(os.Stderr, "error setting sandbox deleted '%s': %v\n", in.SandboxId, err) + } + s.pauseMu.Unlock() snapshotTemplateFiles, err := storage.NewTemplateFiles( From 07426afcceec2bdc7b33e7455b575681c9c16763 Mon Sep 17 00:00:00 2001 From: tycho garen Date: Thu, 6 Mar 2025 18:06:07 -0500 Subject: [PATCH 02/10] chore: switch to sqlc (cherry picked from commit 2bc8680b9bde917cb442a332d620ead5c984d74c) --- packages/orchestrator/internal/db/db.go | 85 +- .../internal/pkg/database/constants.go | 14 + .../orchestrator/internal/pkg/database/db.go | 31 + .../internal/pkg/database/models.go | 27 + .../internal/pkg/database/queries.sql.go | 130 ++ .../internal/pkg/generate_models.go | 3 - .../internal/pkg/models/client.go | 499 ------- .../orchestrator/internal/pkg/models/ent.go | 610 -------- .../internal/pkg/models/enttest/enttest.go | 84 -- .../internal/pkg/models/hook/hook.go | 211 --- .../pkg/models/internal/schemaconfig.go | 25 - .../internal/pkg/models/migrate/migrate.go | 64 - .../internal/pkg/models/migrate/schema.go | 50 - .../internal/pkg/models/mutation.go | 1312 ----------------- .../pkg/models/predicate/predicate.go | 13 - .../internal/pkg/models/runtime.go | 53 - .../internal/pkg/models/runtime/runtime.go | 10 - .../internal/pkg/models/sandbox.go | 189 --- .../internal/pkg/models/sandbox/sandbox.go | 146 -- .../internal/pkg/models/sandbox/where.go | 415 ------ .../internal/pkg/models/sandbox_create.go | 943 ------------ .../internal/pkg/models/sandbox_delete.go | 91 -- .../internal/pkg/models/sandbox_query.go | 556 ------- .../internal/pkg/models/sandbox_update.go | 551 ------- .../internal/pkg/models/status.go | 128 -- .../internal/pkg/models/status/status.go | 101 -- .../internal/pkg/models/status/where.go | 180 --- .../internal/pkg/models/status_create.go | 622 -------- .../internal/pkg/models/status_delete.go | 91 -- .../internal/pkg/models/status_query.go | 556 ------- .../internal/pkg/models/status_update.go | 355 ----- .../orchestrator/internal/pkg/models/tx.go | 213 --- .../internal/pkg/schema/sandbox.go | 32 - .../internal/pkg/schema/status.go | 22 - packages/orchestrator/internal/server/main.go | 2 +- .../orchestrator/internal/server/sandboxes.go | 47 +- packages/orchestrator/queries.sql | 53 + packages/orchestrator/schema.sql | 27 + sqlc.yaml | 24 + 39 files changed, 374 insertions(+), 8191 deletions(-) create mode 100644 packages/orchestrator/internal/pkg/database/constants.go create mode 100644 packages/orchestrator/internal/pkg/database/db.go create mode 100644 packages/orchestrator/internal/pkg/database/models.go create mode 100644 packages/orchestrator/internal/pkg/database/queries.sql.go delete mode 100644 packages/orchestrator/internal/pkg/generate_models.go delete mode 100644 packages/orchestrator/internal/pkg/models/client.go delete mode 100644 packages/orchestrator/internal/pkg/models/ent.go delete mode 100644 packages/orchestrator/internal/pkg/models/enttest/enttest.go delete mode 100644 packages/orchestrator/internal/pkg/models/hook/hook.go delete mode 100644 packages/orchestrator/internal/pkg/models/internal/schemaconfig.go delete mode 100644 packages/orchestrator/internal/pkg/models/migrate/migrate.go delete mode 100644 packages/orchestrator/internal/pkg/models/migrate/schema.go delete mode 100644 packages/orchestrator/internal/pkg/models/mutation.go delete mode 100644 packages/orchestrator/internal/pkg/models/predicate/predicate.go delete mode 100644 packages/orchestrator/internal/pkg/models/runtime.go delete mode 100644 packages/orchestrator/internal/pkg/models/runtime/runtime.go delete mode 100644 packages/orchestrator/internal/pkg/models/sandbox.go delete mode 100644 packages/orchestrator/internal/pkg/models/sandbox/sandbox.go delete mode 100644 packages/orchestrator/internal/pkg/models/sandbox/where.go delete mode 100644 packages/orchestrator/internal/pkg/models/sandbox_create.go delete mode 100644 packages/orchestrator/internal/pkg/models/sandbox_delete.go delete mode 100644 packages/orchestrator/internal/pkg/models/sandbox_query.go delete mode 100644 packages/orchestrator/internal/pkg/models/sandbox_update.go delete mode 100644 packages/orchestrator/internal/pkg/models/status.go delete mode 100644 packages/orchestrator/internal/pkg/models/status/status.go delete mode 100644 packages/orchestrator/internal/pkg/models/status/where.go delete mode 100644 packages/orchestrator/internal/pkg/models/status_create.go delete mode 100644 packages/orchestrator/internal/pkg/models/status_delete.go delete mode 100644 packages/orchestrator/internal/pkg/models/status_query.go delete mode 100644 packages/orchestrator/internal/pkg/models/status_update.go delete mode 100644 packages/orchestrator/internal/pkg/models/tx.go delete mode 100644 packages/orchestrator/internal/pkg/schema/sandbox.go delete mode 100644 packages/orchestrator/internal/pkg/schema/status.go create mode 100644 packages/orchestrator/queries.sql create mode 100644 packages/orchestrator/schema.sql create mode 100644 sqlc.yaml diff --git a/packages/orchestrator/internal/db/db.go b/packages/orchestrator/internal/db/db.go index 44ce366cd..7a18160c9 100644 --- a/packages/orchestrator/internal/db/db.go +++ b/packages/orchestrator/internal/db/db.go @@ -2,68 +2,83 @@ package db import ( "context" + "database/sql" "errors" "time" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/database" + // "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" + // "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" ) type DB struct { - client *models.Client + client *sql.DB + ops *database.Queries } -func (db *DB) Close() error { return db.client.Close() } +func (db *DB) Close() error { + // TODO write terminated state to the status table for + // forensics(?) -func (db *DB) CreateSandbox(ctx context.Context, op func(*models.SandboxCreate)) error { - return db.WithTx(ctx, func(ctx context.Context) error { - now := time.Now() - tx := models.FromContext(ctx) + return db.client.Close() +} - global, err := tx.Status.UpdateOneID(1).AddVersion(1).SetUpdatedAt(now).Save(ctx) - if err != nil { +func (db *DB) CreateSandbox(ctx context.Context, params database.CreateSandboxParams) error { + return db.WithTx(ctx, func(ctx context.Context, op *database.Queries) error { + if _, err := op.IncGlobalVersion(ctx); err != nil { return err } - obj := tx.Sandbox.Create() - op(obj) - obj.SetVersion(1).SetGlobalVersion(global.Version).SetUpdatedAt(now) - if _, err := obj.Save(ctx); err != nil { + if err := op.CreateSandbox(ctx, params); err != nil { return err } - return nil }) } -func (db *DB) UpdateSandbox(ctx context.Context, id string, op func(*models.SandboxUpdateOne)) error { - return db.WithTx(ctx, func(ctx context.Context) error { - now := time.Now() - tx := models.FromContext(ctx) +func (db *DB) UpdateSandboxDeadline(ctx context.Context, id string, deadline time.Time) error { + return db.WithTx(ctx, func(ctx context.Context, op *database.Queries) error { + if _, err := op.IncGlobalVersion(ctx); err != nil { + return err + } - global, err := tx.Status.UpdateOneID(1).AddVersion(1).SetUpdatedAt(now).Save(ctx) - if err != nil { + if err := op.UpdateSandboxDeadline(ctx, database.UpdateSandboxDeadlineParams{ID: id, Deadline: deadline}); err != nil { return err } - obj := tx.Sandbox.UpdateOneID(id) - if err != nil { + return nil + }) +} + +func (db *DB) SetSandboxTerminated(ctx context.Context, id string, duration time.Duration) error { + return db.WithTx(ctx, func(ctx context.Context, op *database.Queries) error { + if _, err := op.IncGlobalVersion(ctx); err != nil { return err } - prev, err := tx.Sandbox.Get(ctx, id) - if err != nil { + if err := op.ShutdownSandbox(ctx, database.ShutdownSandboxParams{ + ID: id, + DurationMs: duration.Milliseconds(), + Status: database.SandboxStatusTerminated, + }); err != nil { return err } - op(obj) - obj = obj.SetUpdatedAt(now).SetGlobalVersion(global.Version).AddVersion(1) - switch prev.Status { - case sandbox.StatusPaused, sandbox.StatusPending, sandbox.StatusTerminated: - obj = obj.AddDurationMs(now.Sub(prev.UpdatedAt).Milliseconds()) + return nil + }) +} + +func (db *DB) SetSandboxPaused(ctx context.Context, id string, duration time.Duration) error { + return db.WithTx(ctx, func(ctx context.Context, op *database.Queries) error { + if _, err := op.IncGlobalVersion(ctx); err != nil { + return err } - if _, err := obj.Save(ctx); err != nil { + if err := op.ShutdownSandbox(ctx, database.ShutdownSandboxParams{ + ID: id, + DurationMs: duration.Milliseconds(), + Status: database.SandboxStatusPaused, + }); err != nil { return err } @@ -71,13 +86,11 @@ func (db *DB) UpdateSandbox(ctx context.Context, id string, op func(*models.Sand }) } -func (db *DB) WithTx(ctx context.Context, op func(context.Context) error) (err error) { - var tx *models.Tx - tx, err = db.client.Tx(ctx) +func (db *DB) WithTx(ctx context.Context, op func(context.Context, *database.Queries) error) (err error) { + tx, err := db.client.BeginTx(ctx, nil) if err != nil { return err } - ctx = models.NewTxContext(ctx, tx) defer func() { if err != nil { err = errors.Join(err, tx.Rollback()) @@ -95,5 +108,5 @@ func (db *DB) WithTx(ctx context.Context, op func(context.Context) error) (err e } }() - return op(ctx) + return op(ctx, db.ops.WithTx(tx)) } diff --git a/packages/orchestrator/internal/pkg/database/constants.go b/packages/orchestrator/internal/pkg/database/constants.go new file mode 100644 index 000000000..898281c0a --- /dev/null +++ b/packages/orchestrator/internal/pkg/database/constants.go @@ -0,0 +1,14 @@ +package database + +const ( + SandboxStatusPending = "pending" + SandboxStatusRunning = "running" + SandboxStatusPaused = "paused" + SandboxStatusTerminated = "terminated" + + OrchestratorStatusInitializing = "initializing" + OrchestratorStatusRunning = "running" + OrchestratorStatusDraining = "draining" + OrchestratorStatusTerminated = "terminated" + OrchestratorStatusQuarantined = "quarantined" +) diff --git a/packages/orchestrator/internal/pkg/database/db.go b/packages/orchestrator/internal/pkg/database/db.go new file mode 100644 index 000000000..bad7c4b9c --- /dev/null +++ b/packages/orchestrator/internal/pkg/database/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.28.0 + +package database + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...interface{}) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...interface{}) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/packages/orchestrator/internal/pkg/database/models.go b/packages/orchestrator/internal/pkg/database/models.go new file mode 100644 index 000000000..8ff01c5f5 --- /dev/null +++ b/packages/orchestrator/internal/pkg/database/models.go @@ -0,0 +1,27 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.28.0 + +package database + +import ( + "time" +) + +type Sandbox struct { + ID string + StartedAt time.Time + UpdatedAt time.Time + Deadline time.Time + Status string + DurationMs int64 + Version int64 + GlobalVersion int64 +} + +type Status struct { + ID int64 + Version int64 + UpdatedAt time.Time + Status string +} diff --git a/packages/orchestrator/internal/pkg/database/queries.sql.go b/packages/orchestrator/internal/pkg/database/queries.sql.go new file mode 100644 index 000000000..42ae14176 --- /dev/null +++ b/packages/orchestrator/internal/pkg/database/queries.sql.go @@ -0,0 +1,130 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.28.0 +// source: queries.sql + +package database + +import ( + "context" + "time" +) + +const createSandbox = `-- name: CreateSandbox :exec +INSERT INTO sandboxes(id, status, started_at, deadline, global_version) +VALUES ( + ?1, + ?2, + ?3, + ?4, + (SELECT version FROM status WHERE status.id = 1) +) +` + +type CreateSandboxParams struct { + ID string + Status string + StartedAt time.Time + Deadline time.Time +} + +func (q *Queries) CreateSandbox(ctx context.Context, arg CreateSandboxParams) error { + _, err := q.db.ExecContext(ctx, createSandbox, + arg.ID, + arg.Status, + arg.StartedAt, + arg.Deadline, + ) + return err +} + +const globalVersion = `-- name: GlobalVersion :one +SELECT version FROM status WHERE id = 1 +` + +func (q *Queries) GlobalVersion(ctx context.Context) (int64, error) { + row := q.db.QueryRowContext(ctx, globalVersion) + var version int64 + err := row.Scan(&version) + return version, err +} + +const incGlobalVersion = `-- name: IncGlobalVersion :one +UPDATE status +SET + version = version + 1, + updated_at = current_timestamp() +WHERE + id = 1 +RETURNING version +` + +func (q *Queries) IncGlobalVersion(ctx context.Context) (int64, error) { + row := q.db.QueryRowContext(ctx, incGlobalVersion) + var version int64 + err := row.Scan(&version) + return version, err +} + +const setGlobalStatus = `-- name: SetGlobalStatus :one +UPDATE status +SET + version = version + 1, + updated_at = current_timestamp(), + status = ?1 +WHERE + id = 1 +RETURNING version +` + +func (q *Queries) SetGlobalStatus(ctx context.Context, status string) (int64, error) { + row := q.db.QueryRowContext(ctx, setGlobalStatus, status) + var version int64 + err := row.Scan(&version) + return version, err +} + +const shutdownSandbox = `-- name: ShutdownSandbox :exec +UPDATE sandboxes +SET + version = version + 1, + global_version = (SELECT version FROM status WHERE status.id = 1), + updated_at = current_timestamp(), + duration_ms = ?1, + status = ?2 +WHERE + sandboxes.id = ?3 +` + +type ShutdownSandboxParams struct { + DurationMs int64 + Status string + ID string +} + +func (q *Queries) ShutdownSandbox(ctx context.Context, arg ShutdownSandboxParams) error { + _, err := q.db.ExecContext(ctx, shutdownSandbox, arg.DurationMs, arg.Status, arg.ID) + return err +} + +const updateSandboxDeadline = `-- name: UpdateSandboxDeadline :exec +UPDATE sandboxes +SET + version = version + 1, + global_version = (SELECT version FROM status WHERE status.id = 1), + udpated_at = current_timestamp(), + deadline = ?1, + status = 'running' +WHERE + sandboxes.id = ?2 +` + +type UpdateSandboxDeadlineParams struct { + Deadline time.Time + ID string +} + +func (q *Queries) UpdateSandboxDeadline(ctx context.Context, arg UpdateSandboxDeadlineParams) error { + _, err := q.db.ExecContext(ctx, updateSandboxDeadline, arg.Deadline, arg.ID) + return err +} diff --git a/packages/orchestrator/internal/pkg/generate_models.go b/packages/orchestrator/internal/pkg/generate_models.go deleted file mode 100644 index b6624c44a..000000000 --- a/packages/orchestrator/internal/pkg/generate_models.go +++ /dev/null @@ -1,3 +0,0 @@ -package pkg - -//go:generate go run entgo.io/ent/cmd/ent generate --feature sql/schemaconfig,sql/upsert,sql/modifier ./schema --target ./models diff --git a/packages/orchestrator/internal/pkg/models/client.go b/packages/orchestrator/internal/pkg/models/client.go deleted file mode 100644 index 2f71ed25b..000000000 --- a/packages/orchestrator/internal/pkg/models/client.go +++ /dev/null @@ -1,499 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "errors" - "fmt" - "log" - "reflect" - - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/migrate" - - "entgo.io/ent" - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" - - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" -) - -// Client is the client that holds all ent builders. -type Client struct { - config - // Schema is the client for creating, migrating and dropping schema. - Schema *migrate.Schema - // Sandbox is the client for interacting with the Sandbox builders. - Sandbox *SandboxClient - // Status is the client for interacting with the Status builders. - Status *StatusClient -} - -// NewClient creates a new client configured with the given options. -func NewClient(opts ...Option) *Client { - client := &Client{config: newConfig(opts...)} - client.init() - return client -} - -func (c *Client) init() { - c.Schema = migrate.NewSchema(c.driver) - c.Sandbox = NewSandboxClient(c.config) - c.Status = NewStatusClient(c.config) -} - -type ( - // config is the configuration for the client and its builder. - config struct { - // driver used for executing database requests. - driver dialect.Driver - // debug enable a debug logging. - debug bool - // log used for logging on debug mode. - log func(...any) - // hooks to execute on mutations. - hooks *hooks - // interceptors to execute on queries. - inters *inters - // schemaConfig contains alternative names for all tables. - schemaConfig SchemaConfig - } - // Option function to configure the client. - Option func(*config) -) - -// newConfig creates a new config for the client. -func newConfig(opts ...Option) config { - cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} - cfg.options(opts...) - return cfg -} - -// options applies the options on the config object. -func (c *config) options(opts ...Option) { - for _, opt := range opts { - opt(c) - } - if c.debug { - c.driver = dialect.Debug(c.driver, c.log) - } -} - -// Debug enables debug logging on the ent.Driver. -func Debug() Option { - return func(c *config) { - c.debug = true - } -} - -// Log sets the logging function for debug mode. -func Log(fn func(...any)) Option { - return func(c *config) { - c.log = fn - } -} - -// Driver configures the client driver. -func Driver(driver dialect.Driver) Option { - return func(c *config) { - c.driver = driver - } -} - -// Open opens a database/sql.DB specified by the driver name and -// the data source name, and returns a new client attached to it. -// Optional parameters can be added for configuring the client. -func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { - switch driverName { - case dialect.MySQL, dialect.Postgres, dialect.SQLite: - drv, err := sql.Open(driverName, dataSourceName) - if err != nil { - return nil, err - } - return NewClient(append(options, Driver(drv))...), nil - default: - return nil, fmt.Errorf("unsupported driver: %q", driverName) - } -} - -// ErrTxStarted is returned when trying to start a new transaction from a transactional client. -var ErrTxStarted = errors.New("models: cannot start a transaction within a transaction") - -// Tx returns a new transactional client. The provided context -// is used until the transaction is committed or rolled back. -func (c *Client) Tx(ctx context.Context) (*Tx, error) { - if _, ok := c.driver.(*txDriver); ok { - return nil, ErrTxStarted - } - tx, err := newTx(ctx, c.driver) - if err != nil { - return nil, fmt.Errorf("models: starting a transaction: %w", err) - } - cfg := c.config - cfg.driver = tx - return &Tx{ - ctx: ctx, - config: cfg, - Sandbox: NewSandboxClient(cfg), - Status: NewStatusClient(cfg), - }, nil -} - -// BeginTx returns a transactional client with specified options. -func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { - if _, ok := c.driver.(*txDriver); ok { - return nil, errors.New("ent: cannot start a transaction within a transaction") - } - tx, err := c.driver.(interface { - BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) - }).BeginTx(ctx, opts) - if err != nil { - return nil, fmt.Errorf("ent: starting a transaction: %w", err) - } - cfg := c.config - cfg.driver = &txDriver{tx: tx, drv: c.driver} - return &Tx{ - ctx: ctx, - config: cfg, - Sandbox: NewSandboxClient(cfg), - Status: NewStatusClient(cfg), - }, nil -} - -// Debug returns a new debug-client. It's used to get verbose logging on specific operations. -// -// client.Debug(). -// Sandbox. -// Query(). -// Count(ctx) -func (c *Client) Debug() *Client { - if c.debug { - return c - } - cfg := c.config - cfg.driver = dialect.Debug(c.driver, c.log) - client := &Client{config: cfg} - client.init() - return client -} - -// Close closes the database connection and prevents new queries from starting. -func (c *Client) Close() error { - return c.driver.Close() -} - -// Use adds the mutation hooks to all the entity clients. -// In order to add hooks to a specific client, call: `client.Node.Use(...)`. -func (c *Client) Use(hooks ...Hook) { - c.Sandbox.Use(hooks...) - c.Status.Use(hooks...) -} - -// Intercept adds the query interceptors to all the entity clients. -// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. -func (c *Client) Intercept(interceptors ...Interceptor) { - c.Sandbox.Intercept(interceptors...) - c.Status.Intercept(interceptors...) -} - -// Mutate implements the ent.Mutator interface. -func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { - switch m := m.(type) { - case *SandboxMutation: - return c.Sandbox.mutate(ctx, m) - case *StatusMutation: - return c.Status.mutate(ctx, m) - default: - return nil, fmt.Errorf("models: unknown mutation type %T", m) - } -} - -// SandboxClient is a client for the Sandbox schema. -type SandboxClient struct { - config -} - -// NewSandboxClient returns a client for the Sandbox from the given config. -func NewSandboxClient(c config) *SandboxClient { - return &SandboxClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `sandbox.Hooks(f(g(h())))`. -func (c *SandboxClient) Use(hooks ...Hook) { - c.hooks.Sandbox = append(c.hooks.Sandbox, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `sandbox.Intercept(f(g(h())))`. -func (c *SandboxClient) Intercept(interceptors ...Interceptor) { - c.inters.Sandbox = append(c.inters.Sandbox, interceptors...) -} - -// Create returns a builder for creating a Sandbox entity. -func (c *SandboxClient) Create() *SandboxCreate { - mutation := newSandboxMutation(c.config, OpCreate) - return &SandboxCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of Sandbox entities. -func (c *SandboxClient) CreateBulk(builders ...*SandboxCreate) *SandboxCreateBulk { - return &SandboxCreateBulk{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 *SandboxClient) MapCreateBulk(slice any, setFunc func(*SandboxCreate, int)) *SandboxCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &SandboxCreateBulk{err: fmt.Errorf("calling to SandboxClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*SandboxCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &SandboxCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for Sandbox. -func (c *SandboxClient) Update() *SandboxUpdate { - mutation := newSandboxMutation(c.config, OpUpdate) - return &SandboxUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *SandboxClient) UpdateOne(s *Sandbox) *SandboxUpdateOne { - mutation := newSandboxMutation(c.config, OpUpdateOne, withSandbox(s)) - return &SandboxUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *SandboxClient) UpdateOneID(id string) *SandboxUpdateOne { - mutation := newSandboxMutation(c.config, OpUpdateOne, withSandboxID(id)) - return &SandboxUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for Sandbox. -func (c *SandboxClient) Delete() *SandboxDelete { - mutation := newSandboxMutation(c.config, OpDelete) - return &SandboxDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *SandboxClient) DeleteOne(s *Sandbox) *SandboxDeleteOne { - return c.DeleteOneID(s.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *SandboxClient) DeleteOneID(id string) *SandboxDeleteOne { - builder := c.Delete().Where(sandbox.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &SandboxDeleteOne{builder} -} - -// Query returns a query builder for Sandbox. -func (c *SandboxClient) Query() *SandboxQuery { - return &SandboxQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeSandbox}, - inters: c.Interceptors(), - } -} - -// Get returns a Sandbox entity by its id. -func (c *SandboxClient) Get(ctx context.Context, id string) (*Sandbox, error) { - return c.Query().Where(sandbox.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *SandboxClient) GetX(ctx context.Context, id string) *Sandbox { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *SandboxClient) Hooks() []Hook { - return c.hooks.Sandbox -} - -// Interceptors returns the client interceptors. -func (c *SandboxClient) Interceptors() []Interceptor { - return c.inters.Sandbox -} - -func (c *SandboxClient) mutate(ctx context.Context, m *SandboxMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&SandboxCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&SandboxUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&SandboxUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&SandboxDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("models: unknown Sandbox mutation op: %q", m.Op()) - } -} - -// StatusClient is a client for the Status schema. -type StatusClient struct { - config -} - -// NewStatusClient returns a client for the Status from the given config. -func NewStatusClient(c config) *StatusClient { - return &StatusClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `status.Hooks(f(g(h())))`. -func (c *StatusClient) Use(hooks ...Hook) { - c.hooks.Status = append(c.hooks.Status, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `status.Intercept(f(g(h())))`. -func (c *StatusClient) Intercept(interceptors ...Interceptor) { - c.inters.Status = append(c.inters.Status, interceptors...) -} - -// Create returns a builder for creating a Status entity. -func (c *StatusClient) Create() *StatusCreate { - mutation := newStatusMutation(c.config, OpCreate) - return &StatusCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of Status entities. -func (c *StatusClient) CreateBulk(builders ...*StatusCreate) *StatusCreateBulk { - return &StatusCreateBulk{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 *StatusClient) MapCreateBulk(slice any, setFunc func(*StatusCreate, int)) *StatusCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &StatusCreateBulk{err: fmt.Errorf("calling to StatusClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*StatusCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &StatusCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for Status. -func (c *StatusClient) Update() *StatusUpdate { - mutation := newStatusMutation(c.config, OpUpdate) - return &StatusUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *StatusClient) UpdateOne(s *Status) *StatusUpdateOne { - mutation := newStatusMutation(c.config, OpUpdateOne, withStatus(s)) - return &StatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *StatusClient) UpdateOneID(id int) *StatusUpdateOne { - mutation := newStatusMutation(c.config, OpUpdateOne, withStatusID(id)) - return &StatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for Status. -func (c *StatusClient) Delete() *StatusDelete { - mutation := newStatusMutation(c.config, OpDelete) - return &StatusDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *StatusClient) DeleteOne(s *Status) *StatusDeleteOne { - return c.DeleteOneID(s.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *StatusClient) DeleteOneID(id int) *StatusDeleteOne { - builder := c.Delete().Where(status.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &StatusDeleteOne{builder} -} - -// Query returns a query builder for Status. -func (c *StatusClient) Query() *StatusQuery { - return &StatusQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeStatus}, - inters: c.Interceptors(), - } -} - -// Get returns a Status entity by its id. -func (c *StatusClient) Get(ctx context.Context, id int) (*Status, error) { - return c.Query().Where(status.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *StatusClient) GetX(ctx context.Context, id int) *Status { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *StatusClient) Hooks() []Hook { - return c.hooks.Status -} - -// Interceptors returns the client interceptors. -func (c *StatusClient) Interceptors() []Interceptor { - return c.inters.Status -} - -func (c *StatusClient) mutate(ctx context.Context, m *StatusMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&StatusCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&StatusUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&StatusUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&StatusDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("models: unknown Status mutation op: %q", m.Op()) - } -} - -// hooks and interceptors per client, for fast access. -type ( - hooks struct { - Sandbox, Status []ent.Hook - } - inters struct { - Sandbox, Status []ent.Interceptor - } -) - -// SchemaConfig represents alternative schema names for all tables -// that can be passed at runtime. -type SchemaConfig = internal.SchemaConfig - -// AlternateSchemas allows alternate schema names to be -// passed into ent operations. -func AlternateSchema(schemaConfig SchemaConfig) Option { - return func(c *config) { - c.schemaConfig = schemaConfig - } -} diff --git a/packages/orchestrator/internal/pkg/models/ent.go b/packages/orchestrator/internal/pkg/models/ent.go deleted file mode 100644 index dac90898d..000000000 --- a/packages/orchestrator/internal/pkg/models/ent.go +++ /dev/null @@ -1,610 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "errors" - "fmt" - "reflect" - "sync" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" -) - -// ent aliases to avoid import conflicts in user's code. -type ( - Op = ent.Op - Hook = ent.Hook - Value = ent.Value - Query = ent.Query - QueryContext = ent.QueryContext - Querier = ent.Querier - QuerierFunc = ent.QuerierFunc - Interceptor = ent.Interceptor - InterceptFunc = ent.InterceptFunc - Traverser = ent.Traverser - TraverseFunc = ent.TraverseFunc - Policy = ent.Policy - Mutator = ent.Mutator - Mutation = ent.Mutation - MutateFunc = ent.MutateFunc -) - -type clientCtxKey struct{} - -// FromContext returns a Client stored inside a context, or nil if there isn't one. -func FromContext(ctx context.Context) *Client { - c, _ := ctx.Value(clientCtxKey{}).(*Client) - return c -} - -// NewContext returns a new context with the given Client attached. -func NewContext(parent context.Context, c *Client) context.Context { - return context.WithValue(parent, clientCtxKey{}, c) -} - -type txCtxKey struct{} - -// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. -func TxFromContext(ctx context.Context) *Tx { - tx, _ := ctx.Value(txCtxKey{}).(*Tx) - return tx -} - -// NewTxContext returns a new context with the given Tx attached. -func NewTxContext(parent context.Context, tx *Tx) context.Context { - return context.WithValue(parent, txCtxKey{}, tx) -} - -// OrderFunc applies an ordering on the sql selector. -// Deprecated: Use Asc/Desc functions or the package builders instead. -type OrderFunc func(*sql.Selector) - -var ( - initCheck sync.Once - columnCheck sql.ColumnCheck -) - -// columnChecker checks if the column exists in the given table. -func checkColumn(table, column string) error { - initCheck.Do(func() { - columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ - sandbox.Table: sandbox.ValidColumn, - status.Table: status.ValidColumn, - }) - }) - return columnCheck(table, column) -} - -// Asc applies the given fields in ASC order. -func Asc(fields ...string) func(*sql.Selector) { - return func(s *sql.Selector) { - for _, f := range fields { - if err := checkColumn(s.TableName(), f); err != nil { - s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) - } - s.OrderBy(sql.Asc(s.C(f))) - } - } -} - -// Desc applies the given fields in DESC order. -func Desc(fields ...string) func(*sql.Selector) { - return func(s *sql.Selector) { - for _, f := range fields { - if err := checkColumn(s.TableName(), f); err != nil { - s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) - } - s.OrderBy(sql.Desc(s.C(f))) - } - } -} - -// AggregateFunc applies an aggregation step on the group-by traversal/selector. -type AggregateFunc func(*sql.Selector) string - -// As is a pseudo aggregation function for renaming another other functions with custom names. For example: -// -// GroupBy(field1, field2). -// Aggregate(models.As(models.Sum(field1), "sum_field1"), (models.As(models.Sum(field2), "sum_field2")). -// Scan(ctx, &v) -func As(fn AggregateFunc, end string) AggregateFunc { - return func(s *sql.Selector) string { - return sql.As(fn(s), end) - } -} - -// Count applies the "count" aggregation function on each group. -func Count() AggregateFunc { - return func(s *sql.Selector) string { - return sql.Count("*") - } -} - -// Max applies the "max" aggregation function on the given field of each group. -func Max(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) - return "" - } - return sql.Max(s.C(field)) - } -} - -// Mean applies the "mean" aggregation function on the given field of each group. -func Mean(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) - return "" - } - return sql.Avg(s.C(field)) - } -} - -// Min applies the "min" aggregation function on the given field of each group. -func Min(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) - return "" - } - return sql.Min(s.C(field)) - } -} - -// Sum applies the "sum" aggregation function on the given field of each group. -func Sum(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) - return "" - } - return sql.Sum(s.C(field)) - } -} - -// ValidationError returns when validating a field or edge fails. -type ValidationError struct { - Name string // Field or edge name. - err error -} - -// Error implements the error interface. -func (e *ValidationError) Error() string { - return e.err.Error() -} - -// Unwrap implements the errors.Wrapper interface. -func (e *ValidationError) Unwrap() error { - return e.err -} - -// IsValidationError returns a boolean indicating whether the error is a validation error. -func IsValidationError(err error) bool { - if err == nil { - return false - } - var e *ValidationError - return errors.As(err, &e) -} - -// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. -type NotFoundError struct { - label string -} - -// Error implements the error interface. -func (e *NotFoundError) Error() string { - return "models: " + e.label + " not found" -} - -// IsNotFound returns a boolean indicating whether the error is a not found error. -func IsNotFound(err error) bool { - if err == nil { - return false - } - var e *NotFoundError - return errors.As(err, &e) -} - -// MaskNotFound masks not found error. -func MaskNotFound(err error) error { - if IsNotFound(err) { - return nil - } - return err -} - -// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. -type NotSingularError struct { - label string -} - -// Error implements the error interface. -func (e *NotSingularError) Error() string { - return "models: " + e.label + " not singular" -} - -// IsNotSingular returns a boolean indicating whether the error is a not singular error. -func IsNotSingular(err error) bool { - if err == nil { - return false - } - var e *NotSingularError - return errors.As(err, &e) -} - -// NotLoadedError returns when trying to get a node that was not loaded by the query. -type NotLoadedError struct { - edge string -} - -// Error implements the error interface. -func (e *NotLoadedError) Error() string { - return "models: " + e.edge + " edge was not loaded" -} - -// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. -func IsNotLoaded(err error) bool { - if err == nil { - return false - } - var e *NotLoadedError - return errors.As(err, &e) -} - -// ConstraintError returns when trying to create/update one or more entities and -// one or more of their constraints failed. For example, violation of edge or -// field uniqueness. -type ConstraintError struct { - msg string - wrap error -} - -// Error implements the error interface. -func (e ConstraintError) Error() string { - return "models: constraint failed: " + e.msg -} - -// Unwrap implements the errors.Wrapper interface. -func (e *ConstraintError) Unwrap() error { - return e.wrap -} - -// IsConstraintError returns a boolean indicating whether the error is a constraint failure. -func IsConstraintError(err error) bool { - if err == nil { - return false - } - var e *ConstraintError - return errors.As(err, &e) -} - -// selector embedded by the different Select/GroupBy builders. -type selector struct { - label string - flds *[]string - fns []AggregateFunc - scan func(context.Context, any) error -} - -// ScanX is like Scan, but panics if an error occurs. -func (s *selector) ScanX(ctx context.Context, v any) { - if err := s.scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (s *selector) Strings(ctx context.Context) ([]string, error) { - if len(*s.flds) > 1 { - return nil, errors.New("models: Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (s *selector) StringsX(ctx context.Context) []string { - v, err := s.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (s *selector) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = s.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("models: Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (s *selector) StringX(ctx context.Context) string { - v, err := s.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (s *selector) Ints(ctx context.Context) ([]int, error) { - if len(*s.flds) > 1 { - return nil, errors.New("models: Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (s *selector) IntsX(ctx context.Context) []int { - v, err := s.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (s *selector) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = s.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("models: Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (s *selector) IntX(ctx context.Context) int { - v, err := s.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (s *selector) Float64s(ctx context.Context) ([]float64, error) { - if len(*s.flds) > 1 { - return nil, errors.New("models: Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (s *selector) Float64sX(ctx context.Context) []float64 { - v, err := s.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (s *selector) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = s.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("models: Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (s *selector) Float64X(ctx context.Context) float64 { - v, err := s.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (s *selector) Bools(ctx context.Context) ([]bool, error) { - if len(*s.flds) > 1 { - return nil, errors.New("models: Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (s *selector) BoolsX(ctx context.Context) []bool { - v, err := s.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (s *selector) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = s.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("models: Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (s *selector) BoolX(ctx context.Context) bool { - v, err := s.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -// withHooks invokes the builder operation with the given hooks, if any. -func withHooks[V Value, M any, PM interface { - *M - Mutation -}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { - if len(hooks) == 0 { - return exec(ctx) - } - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutationT, ok := any(m).(PM) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - // Set the mutation to the builder. - *mutation = *mutationT - return exec(ctx) - }) - for i := len(hooks) - 1; i >= 0; i-- { - if hooks[i] == nil { - return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") - } - mut = hooks[i](mut) - } - v, err := mut.Mutate(ctx, mutation) - if err != nil { - return value, err - } - nv, ok := v.(V) - if !ok { - return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) - } - return nv, nil -} - -// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. -func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { - if ent.QueryFromContext(ctx) == nil { - qc.Op = op - ctx = ent.NewQueryContext(ctx, qc) - } - return ctx -} - -func querierAll[V Value, Q interface { - sqlAll(context.Context, ...queryHook) (V, error) -}]() Querier { - return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - query, ok := q.(Q) - if !ok { - return nil, fmt.Errorf("unexpected query type %T", q) - } - return query.sqlAll(ctx) - }) -} - -func querierCount[Q interface { - sqlCount(context.Context) (int, error) -}]() Querier { - return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - query, ok := q.(Q) - if !ok { - return nil, fmt.Errorf("unexpected query type %T", q) - } - return query.sqlCount(ctx) - }) -} - -func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { - for i := len(inters) - 1; i >= 0; i-- { - qr = inters[i].Intercept(qr) - } - rv, err := qr.Query(ctx, q) - if err != nil { - return v, err - } - vt, ok := rv.(V) - if !ok { - return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) - } - return vt, nil -} - -func scanWithInterceptors[Q1 ent.Query, Q2 interface { - sqlScan(context.Context, Q1, any) error -}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { - rv := reflect.ValueOf(v) - var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - query, ok := q.(Q1) - if !ok { - return nil, fmt.Errorf("unexpected query type %T", q) - } - if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { - return nil, err - } - if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { - return rv.Elem().Interface(), nil - } - return v, nil - }) - for i := len(inters) - 1; i >= 0; i-- { - qr = inters[i].Intercept(qr) - } - vv, err := qr.Query(ctx, rootQuery) - if err != nil { - return err - } - switch rv2 := reflect.ValueOf(vv); { - case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: - case rv.Type() == rv2.Type(): - rv.Elem().Set(rv2.Elem()) - case rv.Elem().Type() == rv2.Type(): - rv.Elem().Set(rv2) - } - return nil -} - -// queryHook describes an internal hook for the different sqlAll methods. -type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/packages/orchestrator/internal/pkg/models/enttest/enttest.go b/packages/orchestrator/internal/pkg/models/enttest/enttest.go deleted file mode 100644 index 8c9f63c40..000000000 --- a/packages/orchestrator/internal/pkg/models/enttest/enttest.go +++ /dev/null @@ -1,84 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package enttest - -import ( - "context" - - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" - // required by schema hooks. - _ "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/runtime" - - "entgo.io/ent/dialect/sql/schema" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/migrate" -) - -type ( - // TestingT is the interface that is shared between - // testing.T and testing.B and used by enttest. - TestingT interface { - FailNow() - Error(...any) - } - - // Option configures client creation. - Option func(*options) - - options struct { - opts []models.Option - migrateOpts []schema.MigrateOption - } -) - -// WithOptions forwards options to client creation. -func WithOptions(opts ...models.Option) Option { - return func(o *options) { - o.opts = append(o.opts, opts...) - } -} - -// WithMigrateOptions forwards options to auto migration. -func WithMigrateOptions(opts ...schema.MigrateOption) Option { - return func(o *options) { - o.migrateOpts = append(o.migrateOpts, opts...) - } -} - -func newOptions(opts []Option) *options { - o := &options{} - for _, opt := range opts { - opt(o) - } - return o -} - -// Open calls models.Open and auto-run migration. -func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *models.Client { - o := newOptions(opts) - c, err := models.Open(driverName, dataSourceName, o.opts...) - if err != nil { - t.Error(err) - t.FailNow() - } - migrateSchema(t, c, o) - return c -} - -// NewClient calls models.NewClient and auto-run migration. -func NewClient(t TestingT, opts ...Option) *models.Client { - o := newOptions(opts) - c := models.NewClient(o.opts...) - migrateSchema(t, c, o) - return c -} -func migrateSchema(t TestingT, c *models.Client, o *options) { - tables, err := schema.CopyTables(migrate.Tables) - if err != nil { - t.Error(err) - t.FailNow() - } - if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { - t.Error(err) - t.FailNow() - } -} diff --git a/packages/orchestrator/internal/pkg/models/hook/hook.go b/packages/orchestrator/internal/pkg/models/hook/hook.go deleted file mode 100644 index 8c677faad..000000000 --- a/packages/orchestrator/internal/pkg/models/hook/hook.go +++ /dev/null @@ -1,211 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package hook - -import ( - "context" - "fmt" - - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" -) - -// The SandboxFunc type is an adapter to allow the use of ordinary -// function as Sandbox mutator. -type SandboxFunc func(context.Context, *models.SandboxMutation) (models.Value, error) - -// Mutate calls f(ctx, m). -func (f SandboxFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { - if mv, ok := m.(*models.SandboxMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *models.SandboxMutation", m) -} - -// The StatusFunc type is an adapter to allow the use of ordinary -// function as Status mutator. -type StatusFunc func(context.Context, *models.StatusMutation) (models.Value, error) - -// Mutate calls f(ctx, m). -func (f StatusFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { - if mv, ok := m.(*models.StatusMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *models.StatusMutation", m) -} - -// Condition is a hook condition function. -type Condition func(context.Context, models.Mutation) bool - -// And groups conditions with the AND operator. -func And(first, second Condition, rest ...Condition) Condition { - return func(ctx context.Context, m models.Mutation) bool { - if !first(ctx, m) || !second(ctx, m) { - return false - } - for _, cond := range rest { - if !cond(ctx, m) { - return false - } - } - return true - } -} - -// Or groups conditions with the OR operator. -func Or(first, second Condition, rest ...Condition) Condition { - return func(ctx context.Context, m models.Mutation) bool { - if first(ctx, m) || second(ctx, m) { - return true - } - for _, cond := range rest { - if cond(ctx, m) { - return true - } - } - return false - } -} - -// Not negates a given condition. -func Not(cond Condition) Condition { - return func(ctx context.Context, m models.Mutation) bool { - return !cond(ctx, m) - } -} - -// HasOp is a condition testing mutation operation. -func HasOp(op models.Op) Condition { - return func(_ context.Context, m models.Mutation) bool { - return m.Op().Is(op) - } -} - -// HasAddedFields is a condition validating `.AddedField` on fields. -func HasAddedFields(field string, fields ...string) Condition { - return func(_ context.Context, m models.Mutation) bool { - if _, exists := m.AddedField(field); !exists { - return false - } - for _, field := range fields { - if _, exists := m.AddedField(field); !exists { - return false - } - } - return true - } -} - -// HasClearedFields is a condition validating `.FieldCleared` on fields. -func HasClearedFields(field string, fields ...string) Condition { - return func(_ context.Context, m models.Mutation) bool { - if exists := m.FieldCleared(field); !exists { - return false - } - for _, field := range fields { - if exists := m.FieldCleared(field); !exists { - return false - } - } - return true - } -} - -// HasFields is a condition validating `.Field` on fields. -func HasFields(field string, fields ...string) Condition { - return func(_ context.Context, m models.Mutation) bool { - if _, exists := m.Field(field); !exists { - return false - } - for _, field := range fields { - if _, exists := m.Field(field); !exists { - return false - } - } - return true - } -} - -// If executes the given hook under condition. -// -// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) -func If(hk models.Hook, cond Condition) models.Hook { - return func(next models.Mutator) models.Mutator { - return models.MutateFunc(func(ctx context.Context, m models.Mutation) (models.Value, error) { - if cond(ctx, m) { - return hk(next).Mutate(ctx, m) - } - return next.Mutate(ctx, m) - }) - } -} - -// On executes the given hook only for the given operation. -// -// hook.On(Log, models.Delete|models.Create) -func On(hk models.Hook, op models.Op) models.Hook { - return If(hk, HasOp(op)) -} - -// Unless skips the given hook only for the given operation. -// -// hook.Unless(Log, models.Update|models.UpdateOne) -func Unless(hk models.Hook, op models.Op) models.Hook { - return If(hk, Not(HasOp(op))) -} - -// FixedError is a hook returning a fixed error. -func FixedError(err error) models.Hook { - return func(models.Mutator) models.Mutator { - return models.MutateFunc(func(context.Context, models.Mutation) (models.Value, error) { - return nil, err - }) - } -} - -// Reject returns a hook that rejects all operations that match op. -// -// func (T) Hooks() []models.Hook { -// return []models.Hook{ -// Reject(models.Delete|models.Update), -// } -// } -func Reject(op models.Op) models.Hook { - hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) - return On(hk, op) -} - -// Chain acts as a list of hooks and is effectively immutable. -// Once created, it will always hold the same set of hooks in the same order. -type Chain struct { - hooks []models.Hook -} - -// NewChain creates a new chain of hooks. -func NewChain(hooks ...models.Hook) Chain { - return Chain{append([]models.Hook(nil), hooks...)} -} - -// Hook chains the list of hooks and returns the final hook. -func (c Chain) Hook() models.Hook { - return func(mutator models.Mutator) models.Mutator { - for i := len(c.hooks) - 1; i >= 0; i-- { - mutator = c.hooks[i](mutator) - } - return mutator - } -} - -// Append extends a chain, adding the specified hook -// as the last ones in the mutation flow. -func (c Chain) Append(hooks ...models.Hook) Chain { - newHooks := make([]models.Hook, 0, len(c.hooks)+len(hooks)) - newHooks = append(newHooks, c.hooks...) - newHooks = append(newHooks, hooks...) - return Chain{newHooks} -} - -// Extend extends a chain, adding the specified chain -// as the last ones in the mutation flow. -func (c Chain) Extend(chain Chain) Chain { - return c.Append(chain.hooks...) -} diff --git a/packages/orchestrator/internal/pkg/models/internal/schemaconfig.go b/packages/orchestrator/internal/pkg/models/internal/schemaconfig.go deleted file mode 100644 index c4dbe072d..000000000 --- a/packages/orchestrator/internal/pkg/models/internal/schemaconfig.go +++ /dev/null @@ -1,25 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package internal - -import "context" - -// SchemaConfig represents alternative schema names for all tables -// that can be passed at runtime. -type SchemaConfig struct { - Sandbox string // Sandbox table. - Status string // Status table. -} - -type schemaCtxKey struct{} - -// SchemaConfigFromContext returns a SchemaConfig stored inside a context, or empty if there isn't one. -func SchemaConfigFromContext(ctx context.Context) SchemaConfig { - config, _ := ctx.Value(schemaCtxKey{}).(SchemaConfig) - return config -} - -// NewSchemaConfigContext returns a new context with the given SchemaConfig attached. -func NewSchemaConfigContext(parent context.Context, config SchemaConfig) context.Context { - return context.WithValue(parent, schemaCtxKey{}, config) -} diff --git a/packages/orchestrator/internal/pkg/models/migrate/migrate.go b/packages/orchestrator/internal/pkg/models/migrate/migrate.go deleted file mode 100644 index 1956a6bf6..000000000 --- a/packages/orchestrator/internal/pkg/models/migrate/migrate.go +++ /dev/null @@ -1,64 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package migrate - -import ( - "context" - "fmt" - "io" - - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql/schema" -) - -var ( - // WithGlobalUniqueID sets the universal ids options to the migration. - // If this option is enabled, ent migration will allocate a 1<<32 range - // for the ids of each entity (table). - // Note that this option cannot be applied on tables that already exist. - WithGlobalUniqueID = schema.WithGlobalUniqueID - // WithDropColumn sets the drop column option to the migration. - // If this option is enabled, ent migration will drop old columns - // that were used for both fields and edges. This defaults to false. - WithDropColumn = schema.WithDropColumn - // WithDropIndex sets the drop index option to the migration. - // If this option is enabled, ent migration will drop old indexes - // that were defined in the schema. This defaults to false. - // Note that unique constraints are defined using `UNIQUE INDEX`, - // and therefore, it's recommended to enable this option to get more - // flexibility in the schema changes. - WithDropIndex = schema.WithDropIndex - // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. - WithForeignKeys = schema.WithForeignKeys -) - -// Schema is the API for creating, migrating and dropping a schema. -type Schema struct { - drv dialect.Driver -} - -// NewSchema creates a new schema client. -func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } - -// Create creates all schema resources. -func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { - return Create(ctx, s, Tables, opts...) -} - -// Create creates all table resources using the given schema driver. -func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { - migrate, err := schema.NewMigrate(s.drv, opts...) - if err != nil { - return fmt.Errorf("ent/migrate: %w", err) - } - return migrate.Create(ctx, tables...) -} - -// WriteTo writes the schema changes to w instead of running them against the database. -// -// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { -// log.Fatal(err) -// } -func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { - return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) -} diff --git a/packages/orchestrator/internal/pkg/models/migrate/schema.go b/packages/orchestrator/internal/pkg/models/migrate/schema.go deleted file mode 100644 index 690460575..000000000 --- a/packages/orchestrator/internal/pkg/models/migrate/schema.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package migrate - -import ( - "entgo.io/ent/dialect/sql/schema" - "entgo.io/ent/schema/field" -) - -var ( - // SandboxesColumns holds the columns for the "sandboxes" table. - SandboxesColumns = []*schema.Column{ - {Name: "id", Type: field.TypeString, Unique: true}, - {Name: "started_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"}, - {Name: "updated_at", Type: field.TypeTime}, - {Name: "terminated_at", Type: field.TypeTime}, - {Name: "deadline", Type: field.TypeTime}, - {Name: "status", Type: field.TypeEnum, Enums: []string{"pending", "running", "paused", "terminated"}}, - {Name: "duration_ms", Type: field.TypeInt64}, - {Name: "version", Type: field.TypeInt64}, - {Name: "global_version", Type: field.TypeInt64}, - } - // SandboxesTable holds the schema information for the "sandboxes" table. - SandboxesTable = &schema.Table{ - Name: "sandboxes", - Columns: SandboxesColumns, - PrimaryKey: []*schema.Column{SandboxesColumns[0]}, - } - // StatusColumns holds the columns for the "status" table. - StatusColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "version", Type: field.TypeInt64, Unique: true}, - {Name: "updated_at", Type: field.TypeTime}, - {Name: "status", Type: field.TypeEnum, Enums: []string{"initializing", "running", "draining", "terminating"}, Default: "running"}, - } - // StatusTable holds the schema information for the "status" table. - StatusTable = &schema.Table{ - Name: "status", - Columns: StatusColumns, - PrimaryKey: []*schema.Column{StatusColumns[0]}, - } - // Tables holds all the tables in the schema. - Tables = []*schema.Table{ - SandboxesTable, - StatusTable, - } -) - -func init() { -} diff --git a/packages/orchestrator/internal/pkg/models/mutation.go b/packages/orchestrator/internal/pkg/models/mutation.go deleted file mode 100644 index 8629fb3ef..000000000 --- a/packages/orchestrator/internal/pkg/models/mutation.go +++ /dev/null @@ -1,1312 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "errors" - "fmt" - "sync" - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" -) - -const ( - // Operation types. - OpCreate = ent.OpCreate - OpDelete = ent.OpDelete - OpDeleteOne = ent.OpDeleteOne - OpUpdate = ent.OpUpdate - OpUpdateOne = ent.OpUpdateOne - - // Node types. - TypeSandbox = "Sandbox" - TypeStatus = "Status" -) - -// SandboxMutation represents an operation that mutates the Sandbox nodes in the graph. -type SandboxMutation struct { - config - op Op - typ string - id *string - started_at *time.Time - updated_at *time.Time - terminated_at *time.Time - deadline *time.Time - status *sandbox.Status - duration_ms *int64 - addduration_ms *int64 - version *int64 - addversion *int64 - global_version *int64 - addglobal_version *int64 - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*Sandbox, error) - predicates []predicate.Sandbox -} - -var _ ent.Mutation = (*SandboxMutation)(nil) - -// sandboxOption allows management of the mutation configuration using functional options. -type sandboxOption func(*SandboxMutation) - -// newSandboxMutation creates new mutation for the Sandbox entity. -func newSandboxMutation(c config, op Op, opts ...sandboxOption) *SandboxMutation { - m := &SandboxMutation{ - config: c, - op: op, - typ: TypeSandbox, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withSandboxID sets the ID field of the mutation. -func withSandboxID(id string) sandboxOption { - return func(m *SandboxMutation) { - var ( - err error - once sync.Once - value *Sandbox - ) - m.oldValue = func(ctx context.Context) (*Sandbox, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Sandbox.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withSandbox sets the old Sandbox of the mutation. -func withSandbox(node *Sandbox) sandboxOption { - return func(m *SandboxMutation) { - m.oldValue = func(context.Context) (*Sandbox, 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 SandboxMutation) 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 SandboxMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("models: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Sandbox entities. -func (m *SandboxMutation) SetID(id string) { - m.id = &id -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *SandboxMutation) ID() (id string, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *SandboxMutation) IDs(ctx context.Context) ([]string, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []string{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().Sandbox.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetStartedAt sets the "started_at" field. -func (m *SandboxMutation) SetStartedAt(t time.Time) { - m.started_at = &t -} - -// StartedAt returns the value of the "started_at" field in the mutation. -func (m *SandboxMutation) StartedAt() (r time.Time, exists bool) { - v := m.started_at - if v == nil { - return - } - return *v, true -} - -// OldStartedAt returns the old "started_at" field's value of the Sandbox entity. -// If the Sandbox 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 *SandboxMutation) OldStartedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStartedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStartedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldStartedAt: %w", err) - } - return oldValue.StartedAt, nil -} - -// ResetStartedAt resets all changes to the "started_at" field. -func (m *SandboxMutation) ResetStartedAt() { - m.started_at = nil -} - -// SetUpdatedAt sets the "updated_at" field. -func (m *SandboxMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t -} - -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *SandboxMutation) 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 Sandbox entity. -// If the Sandbox 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 *SandboxMutation) 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 *SandboxMutation) ResetUpdatedAt() { - m.updated_at = nil -} - -// SetTerminatedAt sets the "terminated_at" field. -func (m *SandboxMutation) SetTerminatedAt(t time.Time) { - m.terminated_at = &t -} - -// TerminatedAt returns the value of the "terminated_at" field in the mutation. -func (m *SandboxMutation) TerminatedAt() (r time.Time, exists bool) { - v := m.terminated_at - if v == nil { - return - } - return *v, true -} - -// OldTerminatedAt returns the old "terminated_at" field's value of the Sandbox entity. -// If the Sandbox 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 *SandboxMutation) OldTerminatedAt(ctx context.Context) (v *time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTerminatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTerminatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTerminatedAt: %w", err) - } - return oldValue.TerminatedAt, nil -} - -// ResetTerminatedAt resets all changes to the "terminated_at" field. -func (m *SandboxMutation) ResetTerminatedAt() { - m.terminated_at = nil -} - -// SetDeadline sets the "deadline" field. -func (m *SandboxMutation) SetDeadline(t time.Time) { - m.deadline = &t -} - -// Deadline returns the value of the "deadline" field in the mutation. -func (m *SandboxMutation) Deadline() (r time.Time, exists bool) { - v := m.deadline - if v == nil { - return - } - return *v, true -} - -// OldDeadline returns the old "deadline" field's value of the Sandbox entity. -// If the Sandbox 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 *SandboxMutation) OldDeadline(ctx context.Context) (v *time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeadline is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeadline requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDeadline: %w", err) - } - return oldValue.Deadline, nil -} - -// ResetDeadline resets all changes to the "deadline" field. -func (m *SandboxMutation) ResetDeadline() { - m.deadline = nil -} - -// SetStatus sets the "status" field. -func (m *SandboxMutation) SetStatus(s sandbox.Status) { - m.status = &s -} - -// Status returns the value of the "status" field in the mutation. -func (m *SandboxMutation) Status() (r sandbox.Status, exists bool) { - v := m.status - if v == nil { - return - } - return *v, true -} - -// OldStatus returns the old "status" field's value of the Sandbox entity. -// If the Sandbox 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 *SandboxMutation) OldStatus(ctx context.Context) (v sandbox.Status, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStatus is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStatus requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldStatus: %w", err) - } - return oldValue.Status, nil -} - -// ResetStatus resets all changes to the "status" field. -func (m *SandboxMutation) ResetStatus() { - m.status = nil -} - -// SetDurationMs sets the "duration_ms" field. -func (m *SandboxMutation) SetDurationMs(i int64) { - m.duration_ms = &i - m.addduration_ms = nil -} - -// DurationMs returns the value of the "duration_ms" field in the mutation. -func (m *SandboxMutation) DurationMs() (r int64, exists bool) { - v := m.duration_ms - if v == nil { - return - } - return *v, true -} - -// OldDurationMs returns the old "duration_ms" field's value of the Sandbox entity. -// If the Sandbox 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 *SandboxMutation) OldDurationMs(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDurationMs is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDurationMs requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDurationMs: %w", err) - } - return oldValue.DurationMs, nil -} - -// AddDurationMs adds i to the "duration_ms" field. -func (m *SandboxMutation) AddDurationMs(i int64) { - if m.addduration_ms != nil { - *m.addduration_ms += i - } else { - m.addduration_ms = &i - } -} - -// AddedDurationMs returns the value that was added to the "duration_ms" field in this mutation. -func (m *SandboxMutation) AddedDurationMs() (r int64, exists bool) { - v := m.addduration_ms - if v == nil { - return - } - return *v, true -} - -// ResetDurationMs resets all changes to the "duration_ms" field. -func (m *SandboxMutation) ResetDurationMs() { - m.duration_ms = nil - m.addduration_ms = nil -} - -// SetVersion sets the "version" field. -func (m *SandboxMutation) SetVersion(i int64) { - m.version = &i - m.addversion = nil -} - -// Version returns the value of the "version" field in the mutation. -func (m *SandboxMutation) Version() (r int64, exists bool) { - v := m.version - if v == nil { - return - } - return *v, true -} - -// OldVersion returns the old "version" field's value of the Sandbox entity. -// If the Sandbox 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 *SandboxMutation) OldVersion(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldVersion is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldVersion requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldVersion: %w", err) - } - return oldValue.Version, nil -} - -// AddVersion adds i to the "version" field. -func (m *SandboxMutation) AddVersion(i int64) { - if m.addversion != nil { - *m.addversion += i - } else { - m.addversion = &i - } -} - -// AddedVersion returns the value that was added to the "version" field in this mutation. -func (m *SandboxMutation) AddedVersion() (r int64, exists bool) { - v := m.addversion - if v == nil { - return - } - return *v, true -} - -// ResetVersion resets all changes to the "version" field. -func (m *SandboxMutation) ResetVersion() { - m.version = nil - m.addversion = nil -} - -// SetGlobalVersion sets the "global_version" field. -func (m *SandboxMutation) SetGlobalVersion(i int64) { - m.global_version = &i - m.addglobal_version = nil -} - -// GlobalVersion returns the value of the "global_version" field in the mutation. -func (m *SandboxMutation) GlobalVersion() (r int64, exists bool) { - v := m.global_version - if v == nil { - return - } - return *v, true -} - -// OldGlobalVersion returns the old "global_version" field's value of the Sandbox entity. -// If the Sandbox 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 *SandboxMutation) OldGlobalVersion(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldGlobalVersion is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldGlobalVersion requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldGlobalVersion: %w", err) - } - return oldValue.GlobalVersion, nil -} - -// AddGlobalVersion adds i to the "global_version" field. -func (m *SandboxMutation) AddGlobalVersion(i int64) { - if m.addglobal_version != nil { - *m.addglobal_version += i - } else { - m.addglobal_version = &i - } -} - -// AddedGlobalVersion returns the value that was added to the "global_version" field in this mutation. -func (m *SandboxMutation) AddedGlobalVersion() (r int64, exists bool) { - v := m.addglobal_version - if v == nil { - return - } - return *v, true -} - -// ResetGlobalVersion resets all changes to the "global_version" field. -func (m *SandboxMutation) ResetGlobalVersion() { - m.global_version = nil - m.addglobal_version = nil -} - -// Where appends a list predicates to the SandboxMutation builder. -func (m *SandboxMutation) Where(ps ...predicate.Sandbox) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the SandboxMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *SandboxMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Sandbox, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *SandboxMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *SandboxMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (Sandbox). -func (m *SandboxMutation) 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 *SandboxMutation) Fields() []string { - fields := make([]string, 0, 8) - if m.started_at != nil { - fields = append(fields, sandbox.FieldStartedAt) - } - if m.updated_at != nil { - fields = append(fields, sandbox.FieldUpdatedAt) - } - if m.terminated_at != nil { - fields = append(fields, sandbox.FieldTerminatedAt) - } - if m.deadline != nil { - fields = append(fields, sandbox.FieldDeadline) - } - if m.status != nil { - fields = append(fields, sandbox.FieldStatus) - } - if m.duration_ms != nil { - fields = append(fields, sandbox.FieldDurationMs) - } - if m.version != nil { - fields = append(fields, sandbox.FieldVersion) - } - if m.global_version != nil { - fields = append(fields, sandbox.FieldGlobalVersion) - } - 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 *SandboxMutation) Field(name string) (ent.Value, bool) { - switch name { - case sandbox.FieldStartedAt: - return m.StartedAt() - case sandbox.FieldUpdatedAt: - return m.UpdatedAt() - case sandbox.FieldTerminatedAt: - return m.TerminatedAt() - case sandbox.FieldDeadline: - return m.Deadline() - case sandbox.FieldStatus: - return m.Status() - case sandbox.FieldDurationMs: - return m.DurationMs() - case sandbox.FieldVersion: - return m.Version() - case sandbox.FieldGlobalVersion: - return m.GlobalVersion() - } - 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 *SandboxMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case sandbox.FieldStartedAt: - return m.OldStartedAt(ctx) - case sandbox.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - case sandbox.FieldTerminatedAt: - return m.OldTerminatedAt(ctx) - case sandbox.FieldDeadline: - return m.OldDeadline(ctx) - case sandbox.FieldStatus: - return m.OldStatus(ctx) - case sandbox.FieldDurationMs: - return m.OldDurationMs(ctx) - case sandbox.FieldVersion: - return m.OldVersion(ctx) - case sandbox.FieldGlobalVersion: - return m.OldGlobalVersion(ctx) - } - return nil, fmt.Errorf("unknown Sandbox 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 *SandboxMutation) SetField(name string, value ent.Value) error { - switch name { - case sandbox.FieldStartedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStartedAt(v) - return nil - case sandbox.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 sandbox.FieldTerminatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTerminatedAt(v) - return nil - case sandbox.FieldDeadline: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeadline(v) - return nil - case sandbox.FieldStatus: - v, ok := value.(sandbox.Status) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatus(v) - return nil - case sandbox.FieldDurationMs: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDurationMs(v) - return nil - case sandbox.FieldVersion: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetVersion(v) - return nil - case sandbox.FieldGlobalVersion: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetGlobalVersion(v) - return nil - } - return fmt.Errorf("unknown Sandbox field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *SandboxMutation) AddedFields() []string { - var fields []string - if m.addduration_ms != nil { - fields = append(fields, sandbox.FieldDurationMs) - } - if m.addversion != nil { - fields = append(fields, sandbox.FieldVersion) - } - if m.addglobal_version != nil { - fields = append(fields, sandbox.FieldGlobalVersion) - } - 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 *SandboxMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case sandbox.FieldDurationMs: - return m.AddedDurationMs() - case sandbox.FieldVersion: - return m.AddedVersion() - case sandbox.FieldGlobalVersion: - return m.AddedGlobalVersion() - } - 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 *SandboxMutation) AddField(name string, value ent.Value) error { - switch name { - case sandbox.FieldDurationMs: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddDurationMs(v) - return nil - case sandbox.FieldVersion: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddVersion(v) - return nil - case sandbox.FieldGlobalVersion: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddGlobalVersion(v) - return nil - } - return fmt.Errorf("unknown Sandbox numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *SandboxMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *SandboxMutation) 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 *SandboxMutation) ClearField(name string) error { - return fmt.Errorf("unknown Sandbox 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 *SandboxMutation) ResetField(name string) error { - switch name { - case sandbox.FieldStartedAt: - m.ResetStartedAt() - return nil - case sandbox.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - case sandbox.FieldTerminatedAt: - m.ResetTerminatedAt() - return nil - case sandbox.FieldDeadline: - m.ResetDeadline() - return nil - case sandbox.FieldStatus: - m.ResetStatus() - return nil - case sandbox.FieldDurationMs: - m.ResetDurationMs() - return nil - case sandbox.FieldVersion: - m.ResetVersion() - return nil - case sandbox.FieldGlobalVersion: - m.ResetGlobalVersion() - return nil - } - return fmt.Errorf("unknown Sandbox field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *SandboxMutation) 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 *SandboxMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *SandboxMutation) 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 *SandboxMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *SandboxMutation) 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 *SandboxMutation) 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 *SandboxMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown Sandbox 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 *SandboxMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown Sandbox edge %s", name) -} - -// StatusMutation represents an operation that mutates the Status nodes in the graph. -type StatusMutation struct { - config - op Op - typ string - id *int - version *int64 - addversion *int64 - updated_at *time.Time - status *status.Status - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*Status, error) - predicates []predicate.Status -} - -var _ ent.Mutation = (*StatusMutation)(nil) - -// statusOption allows management of the mutation configuration using functional options. -type statusOption func(*StatusMutation) - -// newStatusMutation creates new mutation for the Status entity. -func newStatusMutation(c config, op Op, opts ...statusOption) *StatusMutation { - m := &StatusMutation{ - config: c, - op: op, - typ: TypeStatus, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withStatusID sets the ID field of the mutation. -func withStatusID(id int) statusOption { - return func(m *StatusMutation) { - var ( - err error - once sync.Once - value *Status - ) - m.oldValue = func(ctx context.Context) (*Status, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Status.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withStatus sets the old Status of the mutation. -func withStatus(node *Status) statusOption { - return func(m *StatusMutation) { - m.oldValue = func(context.Context) (*Status, 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 StatusMutation) 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 StatusMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("models: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// 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 *StatusMutation) ID() (id int, 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 *StatusMutation) IDs(ctx context.Context) ([]int, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().Status.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetVersion sets the "version" field. -func (m *StatusMutation) SetVersion(i int64) { - m.version = &i - m.addversion = nil -} - -// Version returns the value of the "version" field in the mutation. -func (m *StatusMutation) Version() (r int64, exists bool) { - v := m.version - if v == nil { - return - } - return *v, true -} - -// OldVersion returns the old "version" field's value of the Status entity. -// If the Status 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 *StatusMutation) OldVersion(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldVersion is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldVersion requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldVersion: %w", err) - } - return oldValue.Version, nil -} - -// AddVersion adds i to the "version" field. -func (m *StatusMutation) AddVersion(i int64) { - if m.addversion != nil { - *m.addversion += i - } else { - m.addversion = &i - } -} - -// AddedVersion returns the value that was added to the "version" field in this mutation. -func (m *StatusMutation) AddedVersion() (r int64, exists bool) { - v := m.addversion - if v == nil { - return - } - return *v, true -} - -// ResetVersion resets all changes to the "version" field. -func (m *StatusMutation) ResetVersion() { - m.version = nil - m.addversion = nil -} - -// SetUpdatedAt sets the "updated_at" field. -func (m *StatusMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t -} - -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *StatusMutation) 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 Status entity. -// If the Status 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 *StatusMutation) 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 *StatusMutation) ResetUpdatedAt() { - m.updated_at = nil -} - -// SetStatus sets the "status" field. -func (m *StatusMutation) SetStatus(s status.Status) { - m.status = &s -} - -// Status returns the value of the "status" field in the mutation. -func (m *StatusMutation) Status() (r status.Status, exists bool) { - v := m.status - if v == nil { - return - } - return *v, true -} - -// OldStatus returns the old "status" field's value of the Status entity. -// If the Status 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 *StatusMutation) OldStatus(ctx context.Context) (v status.Status, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStatus is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStatus requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldStatus: %w", err) - } - return oldValue.Status, nil -} - -// ResetStatus resets all changes to the "status" field. -func (m *StatusMutation) ResetStatus() { - m.status = nil -} - -// Where appends a list predicates to the StatusMutation builder. -func (m *StatusMutation) Where(ps ...predicate.Status) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the StatusMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *StatusMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Status, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *StatusMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *StatusMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (Status). -func (m *StatusMutation) 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 *StatusMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.version != nil { - fields = append(fields, status.FieldVersion) - } - if m.updated_at != nil { - fields = append(fields, status.FieldUpdatedAt) - } - if m.status != nil { - fields = append(fields, status.FieldStatus) - } - 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 *StatusMutation) Field(name string) (ent.Value, bool) { - switch name { - case status.FieldVersion: - return m.Version() - case status.FieldUpdatedAt: - return m.UpdatedAt() - case status.FieldStatus: - return m.Status() - } - 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 *StatusMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case status.FieldVersion: - return m.OldVersion(ctx) - case status.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - case status.FieldStatus: - return m.OldStatus(ctx) - } - return nil, fmt.Errorf("unknown Status 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 *StatusMutation) SetField(name string, value ent.Value) error { - switch name { - case status.FieldVersion: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetVersion(v) - return nil - case status.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 status.FieldStatus: - v, ok := value.(status.Status) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatus(v) - return nil - } - return fmt.Errorf("unknown Status field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *StatusMutation) AddedFields() []string { - var fields []string - if m.addversion != nil { - fields = append(fields, status.FieldVersion) - } - 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 *StatusMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case status.FieldVersion: - return m.AddedVersion() - } - 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 *StatusMutation) AddField(name string, value ent.Value) error { - switch name { - case status.FieldVersion: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddVersion(v) - return nil - } - return fmt.Errorf("unknown Status numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *StatusMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *StatusMutation) 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 *StatusMutation) ClearField(name string) error { - return fmt.Errorf("unknown Status 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 *StatusMutation) ResetField(name string) error { - switch name { - case status.FieldVersion: - m.ResetVersion() - return nil - case status.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - case status.FieldStatus: - m.ResetStatus() - return nil - } - return fmt.Errorf("unknown Status field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *StatusMutation) 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 *StatusMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *StatusMutation) 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 *StatusMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *StatusMutation) 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 *StatusMutation) 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 *StatusMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown Status 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 *StatusMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown Status edge %s", name) -} diff --git a/packages/orchestrator/internal/pkg/models/predicate/predicate.go b/packages/orchestrator/internal/pkg/models/predicate/predicate.go deleted file mode 100644 index a80ea017d..000000000 --- a/packages/orchestrator/internal/pkg/models/predicate/predicate.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package predicate - -import ( - "entgo.io/ent/dialect/sql" -) - -// Sandbox is the predicate function for sandbox builders. -type Sandbox func(*sql.Selector) - -// Status is the predicate function for status builders. -type Status func(*sql.Selector) diff --git a/packages/orchestrator/internal/pkg/models/runtime.go b/packages/orchestrator/internal/pkg/models/runtime.go deleted file mode 100644 index c7b19ee1a..000000000 --- a/packages/orchestrator/internal/pkg/models/runtime.go +++ /dev/null @@ -1,53 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "time" - - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/schema" -) - -// The init function reads all schema descriptors with runtime code -// (default values, validators, hooks and policies) and stitches it -// to their package variables. -func init() { - sandboxFields := schema.Sandbox{}.Fields() - _ = sandboxFields - // sandboxDescStartedAt is the schema descriptor for started_at field. - sandboxDescStartedAt := sandboxFields[1].Descriptor() - // sandbox.DefaultStartedAt holds the default value on creation for the started_at field. - sandbox.DefaultStartedAt = sandboxDescStartedAt.Default.(func() time.Time) - // sandboxDescUpdatedAt is the schema descriptor for updated_at field. - sandboxDescUpdatedAt := sandboxFields[2].Descriptor() - // sandbox.DefaultUpdatedAt holds the default value on creation for the updated_at field. - sandbox.DefaultUpdatedAt = sandboxDescUpdatedAt.Default.(func() time.Time) - // sandboxDescDurationMs is the schema descriptor for duration_ms field. - sandboxDescDurationMs := sandboxFields[6].Descriptor() - // sandbox.DurationMsValidator is a validator for the "duration_ms" field. It is called by the builders before save. - sandbox.DurationMsValidator = sandboxDescDurationMs.Validators[0].(func(int64) error) - // sandboxDescVersion is the schema descriptor for version field. - sandboxDescVersion := sandboxFields[7].Descriptor() - // sandbox.VersionValidator is a validator for the "version" field. It is called by the builders before save. - sandbox.VersionValidator = sandboxDescVersion.Validators[0].(func(int64) error) - // sandboxDescGlobalVersion is the schema descriptor for global_version field. - sandboxDescGlobalVersion := sandboxFields[8].Descriptor() - // sandbox.GlobalVersionValidator is a validator for the "global_version" field. It is called by the builders before save. - sandbox.GlobalVersionValidator = sandboxDescGlobalVersion.Validators[0].(func(int64) error) - // sandboxDescID is the schema descriptor for id field. - sandboxDescID := sandboxFields[0].Descriptor() - // sandbox.IDValidator is a validator for the "id" field. It is called by the builders before save. - sandbox.IDValidator = sandboxDescID.Validators[0].(func(string) error) - statusFields := schema.Status{}.Fields() - _ = statusFields - // statusDescVersion is the schema descriptor for version field. - statusDescVersion := statusFields[0].Descriptor() - // status.VersionValidator is a validator for the "version" field. It is called by the builders before save. - status.VersionValidator = statusDescVersion.Validators[0].(func(int64) error) - // statusDescUpdatedAt is the schema descriptor for updated_at field. - statusDescUpdatedAt := statusFields[1].Descriptor() - // status.DefaultUpdatedAt holds the default value on creation for the updated_at field. - status.DefaultUpdatedAt = statusDescUpdatedAt.Default.(func() time.Time) -} diff --git a/packages/orchestrator/internal/pkg/models/runtime/runtime.go b/packages/orchestrator/internal/pkg/models/runtime/runtime.go deleted file mode 100644 index 6cebb1a95..000000000 --- a/packages/orchestrator/internal/pkg/models/runtime/runtime.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package runtime - -// The schema-stitching logic is generated in github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/runtime.go - -const ( - Version = "v0.12.5" // Version of ent codegen. - Sum = "h1:KREM5E4CSoej4zeGa88Ou/gfturAnpUv0mzAjch1sj4=" // Sum of ent codegen. -) diff --git a/packages/orchestrator/internal/pkg/models/sandbox.go b/packages/orchestrator/internal/pkg/models/sandbox.go deleted file mode 100644 index 5050db168..000000000 --- a/packages/orchestrator/internal/pkg/models/sandbox.go +++ /dev/null @@ -1,189 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "fmt" - "strings" - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" -) - -// Sandbox is the model entity for the Sandbox schema. -type Sandbox struct { - config `json:"-"` - // ID of the ent. - ID string `json:"id,omitempty"` - // StartedAt holds the value of the "started_at" field. - StartedAt time.Time `json:"started_at,omitempty"` - // UpdatedAt holds the value of the "updated_at" field. - UpdatedAt time.Time `json:"updated_at,omitempty"` - // TerminatedAt holds the value of the "terminated_at" field. - TerminatedAt *time.Time `json:"terminated_at,omitempty"` - // Deadline holds the value of the "deadline" field. - Deadline *time.Time `json:"deadline,omitempty"` - // Status holds the value of the "status" field. - Status sandbox.Status `json:"status,omitempty"` - // DurationMs holds the value of the "duration_ms" field. - DurationMs int64 `json:"duration_ms,omitempty"` - // an incrementing clock of this - Version int64 `json:"version,omitempty"` - // a record of the version of the global state of the last modification. - GlobalVersion int64 `json:"global_version,omitempty"` - selectValues sql.SelectValues -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*Sandbox) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case sandbox.FieldDurationMs, sandbox.FieldVersion, sandbox.FieldGlobalVersion: - values[i] = new(sql.NullInt64) - case sandbox.FieldID, sandbox.FieldStatus: - values[i] = new(sql.NullString) - case sandbox.FieldStartedAt, sandbox.FieldUpdatedAt, sandbox.FieldTerminatedAt, sandbox.FieldDeadline: - 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 Sandbox fields. -func (s *Sandbox) 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 sandbox.FieldID: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field id", values[i]) - } else if value.Valid { - s.ID = value.String - } - case sandbox.FieldStartedAt: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field started_at", values[i]) - } else if value.Valid { - s.StartedAt = value.Time - } - case sandbox.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 { - s.UpdatedAt = value.Time - } - case sandbox.FieldTerminatedAt: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field terminated_at", values[i]) - } else if value.Valid { - s.TerminatedAt = new(time.Time) - *s.TerminatedAt = value.Time - } - case sandbox.FieldDeadline: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field deadline", values[i]) - } else if value.Valid { - s.Deadline = new(time.Time) - *s.Deadline = value.Time - } - case sandbox.FieldStatus: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field status", values[i]) - } else if value.Valid { - s.Status = sandbox.Status(value.String) - } - case sandbox.FieldDurationMs: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field duration_ms", values[i]) - } else if value.Valid { - s.DurationMs = value.Int64 - } - case sandbox.FieldVersion: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field version", values[i]) - } else if value.Valid { - s.Version = value.Int64 - } - case sandbox.FieldGlobalVersion: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field global_version", values[i]) - } else if value.Valid { - s.GlobalVersion = value.Int64 - } - default: - s.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the Sandbox. -// This includes values selected through modifiers, order, etc. -func (s *Sandbox) Value(name string) (ent.Value, error) { - return s.selectValues.Get(name) -} - -// Update returns a builder for updating this Sandbox. -// Note that you need to call Sandbox.Unwrap() before calling this method if this Sandbox -// was returned from a transaction, and the transaction was committed or rolled back. -func (s *Sandbox) Update() *SandboxUpdateOne { - return NewSandboxClient(s.config).UpdateOne(s) -} - -// Unwrap unwraps the Sandbox 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 (s *Sandbox) Unwrap() *Sandbox { - _tx, ok := s.config.driver.(*txDriver) - if !ok { - panic("models: Sandbox is not a transactional entity") - } - s.config.driver = _tx.drv - return s -} - -// String implements the fmt.Stringer. -func (s *Sandbox) String() string { - var builder strings.Builder - builder.WriteString("Sandbox(") - builder.WriteString(fmt.Sprintf("id=%v, ", s.ID)) - builder.WriteString("started_at=") - builder.WriteString(s.StartedAt.Format(time.ANSIC)) - builder.WriteString(", ") - builder.WriteString("updated_at=") - builder.WriteString(s.UpdatedAt.Format(time.ANSIC)) - builder.WriteString(", ") - if v := s.TerminatedAt; v != nil { - builder.WriteString("terminated_at=") - builder.WriteString(v.Format(time.ANSIC)) - } - builder.WriteString(", ") - if v := s.Deadline; v != nil { - builder.WriteString("deadline=") - builder.WriteString(v.Format(time.ANSIC)) - } - builder.WriteString(", ") - builder.WriteString("status=") - builder.WriteString(fmt.Sprintf("%v", s.Status)) - builder.WriteString(", ") - builder.WriteString("duration_ms=") - builder.WriteString(fmt.Sprintf("%v", s.DurationMs)) - builder.WriteString(", ") - builder.WriteString("version=") - builder.WriteString(fmt.Sprintf("%v", s.Version)) - builder.WriteString(", ") - builder.WriteString("global_version=") - builder.WriteString(fmt.Sprintf("%v", s.GlobalVersion)) - builder.WriteByte(')') - return builder.String() -} - -// Sandboxes is a parsable slice of Sandbox. -type Sandboxes []*Sandbox diff --git a/packages/orchestrator/internal/pkg/models/sandbox/sandbox.go b/packages/orchestrator/internal/pkg/models/sandbox/sandbox.go deleted file mode 100644 index 837747820..000000000 --- a/packages/orchestrator/internal/pkg/models/sandbox/sandbox.go +++ /dev/null @@ -1,146 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package sandbox - -import ( - "fmt" - "time" - - "entgo.io/ent/dialect/sql" -) - -const ( - // Label holds the string label denoting the sandbox type in the database. - Label = "sandbox" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldStartedAt holds the string denoting the started_at field in the database. - FieldStartedAt = "started_at" - // FieldUpdatedAt holds the string denoting the updated_at field in the database. - FieldUpdatedAt = "updated_at" - // FieldTerminatedAt holds the string denoting the terminated_at field in the database. - FieldTerminatedAt = "terminated_at" - // FieldDeadline holds the string denoting the deadline field in the database. - FieldDeadline = "deadline" - // FieldStatus holds the string denoting the status field in the database. - FieldStatus = "status" - // FieldDurationMs holds the string denoting the duration_ms field in the database. - FieldDurationMs = "duration_ms" - // FieldVersion holds the string denoting the version field in the database. - FieldVersion = "version" - // FieldGlobalVersion holds the string denoting the global_version field in the database. - FieldGlobalVersion = "global_version" - // Table holds the table name of the sandbox in the database. - Table = "sandboxes" -) - -// Columns holds all SQL columns for sandbox fields. -var Columns = []string{ - FieldID, - FieldStartedAt, - FieldUpdatedAt, - FieldTerminatedAt, - FieldDeadline, - FieldStatus, - FieldDurationMs, - FieldVersion, - FieldGlobalVersion, -} - -// 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 ( - // DefaultStartedAt holds the default value on creation for the "started_at" field. - DefaultStartedAt func() time.Time - // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. - DefaultUpdatedAt func() time.Time - // DurationMsValidator is a validator for the "duration_ms" field. It is called by the builders before save. - DurationMsValidator func(int64) error - // VersionValidator is a validator for the "version" field. It is called by the builders before save. - VersionValidator func(int64) error - // GlobalVersionValidator is a validator for the "global_version" field. It is called by the builders before save. - GlobalVersionValidator func(int64) error - // IDValidator is a validator for the "id" field. It is called by the builders before save. - IDValidator func(string) error -) - -// Status defines the type for the "status" enum field. -type Status string - -// Status values. -const ( - StatusPending Status = "pending" - StatusRunning Status = "running" - StatusPaused Status = "paused" - StatusTerminated Status = "terminated" -) - -func (s Status) String() string { - return string(s) -} - -// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. -func StatusValidator(s Status) error { - switch s { - case StatusPending, StatusRunning, StatusPaused, StatusTerminated: - return nil - default: - return fmt.Errorf("sandbox: invalid enum value for status field: %q", s) - } -} - -// OrderOption defines the ordering options for the Sandbox 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() -} - -// ByStartedAt orders the results by the started_at field. -func ByStartedAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldStartedAt, opts...).ToFunc() -} - -// ByUpdatedAt orders the results by the updated_at field. -func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() -} - -// ByTerminatedAt orders the results by the terminated_at field. -func ByTerminatedAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldTerminatedAt, opts...).ToFunc() -} - -// ByDeadline orders the results by the deadline field. -func ByDeadline(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldDeadline, opts...).ToFunc() -} - -// ByStatus orders the results by the status field. -func ByStatus(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldStatus, opts...).ToFunc() -} - -// ByDurationMs orders the results by the duration_ms field. -func ByDurationMs(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldDurationMs, opts...).ToFunc() -} - -// ByVersion orders the results by the version field. -func ByVersion(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldVersion, opts...).ToFunc() -} - -// ByGlobalVersion orders the results by the global_version field. -func ByGlobalVersion(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldGlobalVersion, opts...).ToFunc() -} diff --git a/packages/orchestrator/internal/pkg/models/sandbox/where.go b/packages/orchestrator/internal/pkg/models/sandbox/where.go deleted file mode 100644 index db105d87a..000000000 --- a/packages/orchestrator/internal/pkg/models/sandbox/where.go +++ /dev/null @@ -1,415 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package sandbox - -import ( - "time" - - "entgo.io/ent/dialect/sql" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLTE(FieldID, id)) -} - -// IDEqualFold applies the EqualFold predicate on the ID field. -func IDEqualFold(id string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEqualFold(FieldID, id)) -} - -// IDContainsFold applies the ContainsFold predicate on the ID field. -func IDContainsFold(id string) predicate.Sandbox { - return predicate.Sandbox(sql.FieldContainsFold(FieldID, id)) -} - -// StartedAt applies equality check predicate on the "started_at" field. It's identical to StartedAtEQ. -func StartedAt(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldStartedAt, v)) -} - -// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. -func UpdatedAt(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldUpdatedAt, v)) -} - -// TerminatedAt applies equality check predicate on the "terminated_at" field. It's identical to TerminatedAtEQ. -func TerminatedAt(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldTerminatedAt, v)) -} - -// Deadline applies equality check predicate on the "deadline" field. It's identical to DeadlineEQ. -func Deadline(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldDeadline, v)) -} - -// DurationMs applies equality check predicate on the "duration_ms" field. It's identical to DurationMsEQ. -func DurationMs(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldDurationMs, v)) -} - -// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. -func Version(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldVersion, v)) -} - -// GlobalVersion applies equality check predicate on the "global_version" field. It's identical to GlobalVersionEQ. -func GlobalVersion(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldGlobalVersion, v)) -} - -// StartedAtEQ applies the EQ predicate on the "started_at" field. -func StartedAtEQ(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldStartedAt, v)) -} - -// StartedAtNEQ applies the NEQ predicate on the "started_at" field. -func StartedAtNEQ(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNEQ(FieldStartedAt, v)) -} - -// StartedAtIn applies the In predicate on the "started_at" field. -func StartedAtIn(vs ...time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldIn(FieldStartedAt, vs...)) -} - -// StartedAtNotIn applies the NotIn predicate on the "started_at" field. -func StartedAtNotIn(vs ...time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNotIn(FieldStartedAt, vs...)) -} - -// StartedAtGT applies the GT predicate on the "started_at" field. -func StartedAtGT(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGT(FieldStartedAt, v)) -} - -// StartedAtGTE applies the GTE predicate on the "started_at" field. -func StartedAtGTE(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGTE(FieldStartedAt, v)) -} - -// StartedAtLT applies the LT predicate on the "started_at" field. -func StartedAtLT(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLT(FieldStartedAt, v)) -} - -// StartedAtLTE applies the LTE predicate on the "started_at" field. -func StartedAtLTE(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLTE(FieldStartedAt, v)) -} - -// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. -func UpdatedAtEQ(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldUpdatedAt, v)) -} - -// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. -func UpdatedAtNEQ(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNEQ(FieldUpdatedAt, v)) -} - -// UpdatedAtIn applies the In predicate on the "updated_at" field. -func UpdatedAtIn(vs ...time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldIn(FieldUpdatedAt, vs...)) -} - -// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. -func UpdatedAtNotIn(vs ...time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNotIn(FieldUpdatedAt, vs...)) -} - -// UpdatedAtGT applies the GT predicate on the "updated_at" field. -func UpdatedAtGT(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGT(FieldUpdatedAt, v)) -} - -// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. -func UpdatedAtGTE(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGTE(FieldUpdatedAt, v)) -} - -// UpdatedAtLT applies the LT predicate on the "updated_at" field. -func UpdatedAtLT(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLT(FieldUpdatedAt, v)) -} - -// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. -func UpdatedAtLTE(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLTE(FieldUpdatedAt, v)) -} - -// TerminatedAtEQ applies the EQ predicate on the "terminated_at" field. -func TerminatedAtEQ(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldTerminatedAt, v)) -} - -// TerminatedAtNEQ applies the NEQ predicate on the "terminated_at" field. -func TerminatedAtNEQ(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNEQ(FieldTerminatedAt, v)) -} - -// TerminatedAtIn applies the In predicate on the "terminated_at" field. -func TerminatedAtIn(vs ...time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldIn(FieldTerminatedAt, vs...)) -} - -// TerminatedAtNotIn applies the NotIn predicate on the "terminated_at" field. -func TerminatedAtNotIn(vs ...time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNotIn(FieldTerminatedAt, vs...)) -} - -// TerminatedAtGT applies the GT predicate on the "terminated_at" field. -func TerminatedAtGT(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGT(FieldTerminatedAt, v)) -} - -// TerminatedAtGTE applies the GTE predicate on the "terminated_at" field. -func TerminatedAtGTE(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGTE(FieldTerminatedAt, v)) -} - -// TerminatedAtLT applies the LT predicate on the "terminated_at" field. -func TerminatedAtLT(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLT(FieldTerminatedAt, v)) -} - -// TerminatedAtLTE applies the LTE predicate on the "terminated_at" field. -func TerminatedAtLTE(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLTE(FieldTerminatedAt, v)) -} - -// DeadlineEQ applies the EQ predicate on the "deadline" field. -func DeadlineEQ(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldDeadline, v)) -} - -// DeadlineNEQ applies the NEQ predicate on the "deadline" field. -func DeadlineNEQ(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNEQ(FieldDeadline, v)) -} - -// DeadlineIn applies the In predicate on the "deadline" field. -func DeadlineIn(vs ...time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldIn(FieldDeadline, vs...)) -} - -// DeadlineNotIn applies the NotIn predicate on the "deadline" field. -func DeadlineNotIn(vs ...time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNotIn(FieldDeadline, vs...)) -} - -// DeadlineGT applies the GT predicate on the "deadline" field. -func DeadlineGT(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGT(FieldDeadline, v)) -} - -// DeadlineGTE applies the GTE predicate on the "deadline" field. -func DeadlineGTE(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGTE(FieldDeadline, v)) -} - -// DeadlineLT applies the LT predicate on the "deadline" field. -func DeadlineLT(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLT(FieldDeadline, v)) -} - -// DeadlineLTE applies the LTE predicate on the "deadline" field. -func DeadlineLTE(v time.Time) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLTE(FieldDeadline, v)) -} - -// StatusEQ applies the EQ predicate on the "status" field. -func StatusEQ(v Status) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldStatus, v)) -} - -// StatusNEQ applies the NEQ predicate on the "status" field. -func StatusNEQ(v Status) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNEQ(FieldStatus, v)) -} - -// StatusIn applies the In predicate on the "status" field. -func StatusIn(vs ...Status) predicate.Sandbox { - return predicate.Sandbox(sql.FieldIn(FieldStatus, vs...)) -} - -// StatusNotIn applies the NotIn predicate on the "status" field. -func StatusNotIn(vs ...Status) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNotIn(FieldStatus, vs...)) -} - -// DurationMsEQ applies the EQ predicate on the "duration_ms" field. -func DurationMsEQ(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldDurationMs, v)) -} - -// DurationMsNEQ applies the NEQ predicate on the "duration_ms" field. -func DurationMsNEQ(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNEQ(FieldDurationMs, v)) -} - -// DurationMsIn applies the In predicate on the "duration_ms" field. -func DurationMsIn(vs ...int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldIn(FieldDurationMs, vs...)) -} - -// DurationMsNotIn applies the NotIn predicate on the "duration_ms" field. -func DurationMsNotIn(vs ...int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNotIn(FieldDurationMs, vs...)) -} - -// DurationMsGT applies the GT predicate on the "duration_ms" field. -func DurationMsGT(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGT(FieldDurationMs, v)) -} - -// DurationMsGTE applies the GTE predicate on the "duration_ms" field. -func DurationMsGTE(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGTE(FieldDurationMs, v)) -} - -// DurationMsLT applies the LT predicate on the "duration_ms" field. -func DurationMsLT(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLT(FieldDurationMs, v)) -} - -// DurationMsLTE applies the LTE predicate on the "duration_ms" field. -func DurationMsLTE(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLTE(FieldDurationMs, v)) -} - -// VersionEQ applies the EQ predicate on the "version" field. -func VersionEQ(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldVersion, v)) -} - -// VersionNEQ applies the NEQ predicate on the "version" field. -func VersionNEQ(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNEQ(FieldVersion, v)) -} - -// VersionIn applies the In predicate on the "version" field. -func VersionIn(vs ...int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldIn(FieldVersion, vs...)) -} - -// VersionNotIn applies the NotIn predicate on the "version" field. -func VersionNotIn(vs ...int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNotIn(FieldVersion, vs...)) -} - -// VersionGT applies the GT predicate on the "version" field. -func VersionGT(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGT(FieldVersion, v)) -} - -// VersionGTE applies the GTE predicate on the "version" field. -func VersionGTE(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGTE(FieldVersion, v)) -} - -// VersionLT applies the LT predicate on the "version" field. -func VersionLT(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLT(FieldVersion, v)) -} - -// VersionLTE applies the LTE predicate on the "version" field. -func VersionLTE(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLTE(FieldVersion, v)) -} - -// GlobalVersionEQ applies the EQ predicate on the "global_version" field. -func GlobalVersionEQ(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldEQ(FieldGlobalVersion, v)) -} - -// GlobalVersionNEQ applies the NEQ predicate on the "global_version" field. -func GlobalVersionNEQ(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNEQ(FieldGlobalVersion, v)) -} - -// GlobalVersionIn applies the In predicate on the "global_version" field. -func GlobalVersionIn(vs ...int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldIn(FieldGlobalVersion, vs...)) -} - -// GlobalVersionNotIn applies the NotIn predicate on the "global_version" field. -func GlobalVersionNotIn(vs ...int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldNotIn(FieldGlobalVersion, vs...)) -} - -// GlobalVersionGT applies the GT predicate on the "global_version" field. -func GlobalVersionGT(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGT(FieldGlobalVersion, v)) -} - -// GlobalVersionGTE applies the GTE predicate on the "global_version" field. -func GlobalVersionGTE(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldGTE(FieldGlobalVersion, v)) -} - -// GlobalVersionLT applies the LT predicate on the "global_version" field. -func GlobalVersionLT(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLT(FieldGlobalVersion, v)) -} - -// GlobalVersionLTE applies the LTE predicate on the "global_version" field. -func GlobalVersionLTE(v int64) predicate.Sandbox { - return predicate.Sandbox(sql.FieldLTE(FieldGlobalVersion, v)) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.Sandbox) predicate.Sandbox { - return predicate.Sandbox(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.Sandbox) predicate.Sandbox { - return predicate.Sandbox(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.Sandbox) predicate.Sandbox { - return predicate.Sandbox(sql.NotPredicates(p)) -} diff --git a/packages/orchestrator/internal/pkg/models/sandbox_create.go b/packages/orchestrator/internal/pkg/models/sandbox_create.go deleted file mode 100644 index a951a1405..000000000 --- a/packages/orchestrator/internal/pkg/models/sandbox_create.go +++ /dev/null @@ -1,943 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" -) - -// SandboxCreate is the builder for creating a Sandbox entity. -type SandboxCreate struct { - config - mutation *SandboxMutation - hooks []Hook - conflict []sql.ConflictOption -} - -// SetStartedAt sets the "started_at" field. -func (sc *SandboxCreate) SetStartedAt(t time.Time) *SandboxCreate { - sc.mutation.SetStartedAt(t) - return sc -} - -// SetNillableStartedAt sets the "started_at" field if the given value is not nil. -func (sc *SandboxCreate) SetNillableStartedAt(t *time.Time) *SandboxCreate { - if t != nil { - sc.SetStartedAt(*t) - } - return sc -} - -// SetUpdatedAt sets the "updated_at" field. -func (sc *SandboxCreate) SetUpdatedAt(t time.Time) *SandboxCreate { - sc.mutation.SetUpdatedAt(t) - return sc -} - -// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. -func (sc *SandboxCreate) SetNillableUpdatedAt(t *time.Time) *SandboxCreate { - if t != nil { - sc.SetUpdatedAt(*t) - } - return sc -} - -// SetTerminatedAt sets the "terminated_at" field. -func (sc *SandboxCreate) SetTerminatedAt(t time.Time) *SandboxCreate { - sc.mutation.SetTerminatedAt(t) - return sc -} - -// SetDeadline sets the "deadline" field. -func (sc *SandboxCreate) SetDeadline(t time.Time) *SandboxCreate { - sc.mutation.SetDeadline(t) - return sc -} - -// SetStatus sets the "status" field. -func (sc *SandboxCreate) SetStatus(s sandbox.Status) *SandboxCreate { - sc.mutation.SetStatus(s) - return sc -} - -// SetDurationMs sets the "duration_ms" field. -func (sc *SandboxCreate) SetDurationMs(i int64) *SandboxCreate { - sc.mutation.SetDurationMs(i) - return sc -} - -// SetVersion sets the "version" field. -func (sc *SandboxCreate) SetVersion(i int64) *SandboxCreate { - sc.mutation.SetVersion(i) - return sc -} - -// SetGlobalVersion sets the "global_version" field. -func (sc *SandboxCreate) SetGlobalVersion(i int64) *SandboxCreate { - sc.mutation.SetGlobalVersion(i) - return sc -} - -// SetID sets the "id" field. -func (sc *SandboxCreate) SetID(s string) *SandboxCreate { - sc.mutation.SetID(s) - return sc -} - -// Mutation returns the SandboxMutation object of the builder. -func (sc *SandboxCreate) Mutation() *SandboxMutation { - return sc.mutation -} - -// Save creates the Sandbox in the database. -func (sc *SandboxCreate) Save(ctx context.Context) (*Sandbox, error) { - sc.defaults() - return withHooks(ctx, sc.sqlSave, sc.mutation, sc.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (sc *SandboxCreate) SaveX(ctx context.Context) *Sandbox { - v, err := sc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (sc *SandboxCreate) Exec(ctx context.Context) error { - _, err := sc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (sc *SandboxCreate) ExecX(ctx context.Context) { - if err := sc.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (sc *SandboxCreate) defaults() { - if _, ok := sc.mutation.StartedAt(); !ok { - v := sandbox.DefaultStartedAt() - sc.mutation.SetStartedAt(v) - } - if _, ok := sc.mutation.UpdatedAt(); !ok { - v := sandbox.DefaultUpdatedAt() - sc.mutation.SetUpdatedAt(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (sc *SandboxCreate) check() error { - if _, ok := sc.mutation.StartedAt(); !ok { - return &ValidationError{Name: "started_at", err: errors.New(`models: missing required field "Sandbox.started_at"`)} - } - if _, ok := sc.mutation.UpdatedAt(); !ok { - return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Sandbox.updated_at"`)} - } - if _, ok := sc.mutation.TerminatedAt(); !ok { - return &ValidationError{Name: "terminated_at", err: errors.New(`models: missing required field "Sandbox.terminated_at"`)} - } - if _, ok := sc.mutation.Deadline(); !ok { - return &ValidationError{Name: "deadline", err: errors.New(`models: missing required field "Sandbox.deadline"`)} - } - if _, ok := sc.mutation.Status(); !ok { - return &ValidationError{Name: "status", err: errors.New(`models: missing required field "Sandbox.status"`)} - } - if v, ok := sc.mutation.Status(); ok { - if err := sandbox.StatusValidator(v); err != nil { - return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Sandbox.status": %w`, err)} - } - } - if _, ok := sc.mutation.DurationMs(); !ok { - return &ValidationError{Name: "duration_ms", err: errors.New(`models: missing required field "Sandbox.duration_ms"`)} - } - if v, ok := sc.mutation.DurationMs(); ok { - if err := sandbox.DurationMsValidator(v); err != nil { - return &ValidationError{Name: "duration_ms", err: fmt.Errorf(`models: validator failed for field "Sandbox.duration_ms": %w`, err)} - } - } - if _, ok := sc.mutation.Version(); !ok { - return &ValidationError{Name: "version", err: errors.New(`models: missing required field "Sandbox.version"`)} - } - if v, ok := sc.mutation.Version(); ok { - if err := sandbox.VersionValidator(v); err != nil { - return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Sandbox.version": %w`, err)} - } - } - if _, ok := sc.mutation.GlobalVersion(); !ok { - return &ValidationError{Name: "global_version", err: errors.New(`models: missing required field "Sandbox.global_version"`)} - } - if v, ok := sc.mutation.GlobalVersion(); ok { - if err := sandbox.GlobalVersionValidator(v); err != nil { - return &ValidationError{Name: "global_version", err: fmt.Errorf(`models: validator failed for field "Sandbox.global_version": %w`, err)} - } - } - if v, ok := sc.mutation.ID(); ok { - if err := sandbox.IDValidator(v); err != nil { - return &ValidationError{Name: "id", err: fmt.Errorf(`models: validator failed for field "Sandbox.id": %w`, err)} - } - } - return nil -} - -func (sc *SandboxCreate) sqlSave(ctx context.Context) (*Sandbox, error) { - if err := sc.check(); err != nil { - return nil, err - } - _node, _spec := sc.createSpec() - if err := sqlgraph.CreateNode(ctx, sc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - if _spec.ID.Value != nil { - if id, ok := _spec.ID.Value.(string); ok { - _node.ID = id - } else { - return nil, fmt.Errorf("unexpected Sandbox.ID type: %T", _spec.ID.Value) - } - } - sc.mutation.id = &_node.ID - sc.mutation.done = true - return _node, nil -} - -func (sc *SandboxCreate) createSpec() (*Sandbox, *sqlgraph.CreateSpec) { - var ( - _node = &Sandbox{config: sc.config} - _spec = sqlgraph.NewCreateSpec(sandbox.Table, sqlgraph.NewFieldSpec(sandbox.FieldID, field.TypeString)) - ) - _spec.Schema = sc.schemaConfig.Sandbox - _spec.OnConflict = sc.conflict - if id, ok := sc.mutation.ID(); ok { - _node.ID = id - _spec.ID.Value = id - } - if value, ok := sc.mutation.StartedAt(); ok { - _spec.SetField(sandbox.FieldStartedAt, field.TypeTime, value) - _node.StartedAt = value - } - if value, ok := sc.mutation.UpdatedAt(); ok { - _spec.SetField(sandbox.FieldUpdatedAt, field.TypeTime, value) - _node.UpdatedAt = value - } - if value, ok := sc.mutation.TerminatedAt(); ok { - _spec.SetField(sandbox.FieldTerminatedAt, field.TypeTime, value) - _node.TerminatedAt = &value - } - if value, ok := sc.mutation.Deadline(); ok { - _spec.SetField(sandbox.FieldDeadline, field.TypeTime, value) - _node.Deadline = &value - } - if value, ok := sc.mutation.Status(); ok { - _spec.SetField(sandbox.FieldStatus, field.TypeEnum, value) - _node.Status = value - } - if value, ok := sc.mutation.DurationMs(); ok { - _spec.SetField(sandbox.FieldDurationMs, field.TypeInt64, value) - _node.DurationMs = value - } - if value, ok := sc.mutation.Version(); ok { - _spec.SetField(sandbox.FieldVersion, field.TypeInt64, value) - _node.Version = value - } - if value, ok := sc.mutation.GlobalVersion(); ok { - _spec.SetField(sandbox.FieldGlobalVersion, field.TypeInt64, value) - _node.GlobalVersion = value - } - return _node, _spec -} - -// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause -// of the `INSERT` statement. For example: -// -// client.Sandbox.Create(). -// SetStartedAt(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.SandboxUpsert) { -// SetStartedAt(v+v). -// }). -// Exec(ctx) -func (sc *SandboxCreate) OnConflict(opts ...sql.ConflictOption) *SandboxUpsertOne { - sc.conflict = opts - return &SandboxUpsertOne{ - create: sc, - } -} - -// OnConflictColumns calls `OnConflict` and configures the columns -// as conflict target. Using this option is equivalent to using: -// -// client.Sandbox.Create(). -// OnConflict(sql.ConflictColumns(columns...)). -// Exec(ctx) -func (sc *SandboxCreate) OnConflictColumns(columns ...string) *SandboxUpsertOne { - sc.conflict = append(sc.conflict, sql.ConflictColumns(columns...)) - return &SandboxUpsertOne{ - create: sc, - } -} - -type ( - // SandboxUpsertOne is the builder for "upsert"-ing - // one Sandbox node. - SandboxUpsertOne struct { - create *SandboxCreate - } - - // SandboxUpsert is the "OnConflict" setter. - SandboxUpsert struct { - *sql.UpdateSet - } -) - -// SetUpdatedAt sets the "updated_at" field. -func (u *SandboxUpsert) SetUpdatedAt(v time.Time) *SandboxUpsert { - u.Set(sandbox.FieldUpdatedAt, v) - return u -} - -// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. -func (u *SandboxUpsert) UpdateUpdatedAt() *SandboxUpsert { - u.SetExcluded(sandbox.FieldUpdatedAt) - return u -} - -// SetTerminatedAt sets the "terminated_at" field. -func (u *SandboxUpsert) SetTerminatedAt(v time.Time) *SandboxUpsert { - u.Set(sandbox.FieldTerminatedAt, v) - return u -} - -// UpdateTerminatedAt sets the "terminated_at" field to the value that was provided on create. -func (u *SandboxUpsert) UpdateTerminatedAt() *SandboxUpsert { - u.SetExcluded(sandbox.FieldTerminatedAt) - return u -} - -// SetDeadline sets the "deadline" field. -func (u *SandboxUpsert) SetDeadline(v time.Time) *SandboxUpsert { - u.Set(sandbox.FieldDeadline, v) - return u -} - -// UpdateDeadline sets the "deadline" field to the value that was provided on create. -func (u *SandboxUpsert) UpdateDeadline() *SandboxUpsert { - u.SetExcluded(sandbox.FieldDeadline) - return u -} - -// SetStatus sets the "status" field. -func (u *SandboxUpsert) SetStatus(v sandbox.Status) *SandboxUpsert { - u.Set(sandbox.FieldStatus, v) - return u -} - -// UpdateStatus sets the "status" field to the value that was provided on create. -func (u *SandboxUpsert) UpdateStatus() *SandboxUpsert { - u.SetExcluded(sandbox.FieldStatus) - return u -} - -// SetDurationMs sets the "duration_ms" field. -func (u *SandboxUpsert) SetDurationMs(v int64) *SandboxUpsert { - u.Set(sandbox.FieldDurationMs, v) - return u -} - -// UpdateDurationMs sets the "duration_ms" field to the value that was provided on create. -func (u *SandboxUpsert) UpdateDurationMs() *SandboxUpsert { - u.SetExcluded(sandbox.FieldDurationMs) - return u -} - -// AddDurationMs adds v to the "duration_ms" field. -func (u *SandboxUpsert) AddDurationMs(v int64) *SandboxUpsert { - u.Add(sandbox.FieldDurationMs, v) - return u -} - -// SetVersion sets the "version" field. -func (u *SandboxUpsert) SetVersion(v int64) *SandboxUpsert { - u.Set(sandbox.FieldVersion, v) - return u -} - -// UpdateVersion sets the "version" field to the value that was provided on create. -func (u *SandboxUpsert) UpdateVersion() *SandboxUpsert { - u.SetExcluded(sandbox.FieldVersion) - return u -} - -// AddVersion adds v to the "version" field. -func (u *SandboxUpsert) AddVersion(v int64) *SandboxUpsert { - u.Add(sandbox.FieldVersion, v) - return u -} - -// SetGlobalVersion sets the "global_version" field. -func (u *SandboxUpsert) SetGlobalVersion(v int64) *SandboxUpsert { - u.Set(sandbox.FieldGlobalVersion, v) - return u -} - -// UpdateGlobalVersion sets the "global_version" field to the value that was provided on create. -func (u *SandboxUpsert) UpdateGlobalVersion() *SandboxUpsert { - u.SetExcluded(sandbox.FieldGlobalVersion) - return u -} - -// AddGlobalVersion adds v to the "global_version" field. -func (u *SandboxUpsert) AddGlobalVersion(v int64) *SandboxUpsert { - u.Add(sandbox.FieldGlobalVersion, v) - return u -} - -// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. -// Using this option is equivalent to using: -// -// client.Sandbox.Create(). -// OnConflict( -// sql.ResolveWithNewValues(), -// sql.ResolveWith(func(u *sql.UpdateSet) { -// u.SetIgnore(sandbox.FieldID) -// }), -// ). -// Exec(ctx) -func (u *SandboxUpsertOne) UpdateNewValues() *SandboxUpsertOne { - u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { - if _, exists := u.create.mutation.ID(); exists { - s.SetIgnore(sandbox.FieldID) - } - if _, exists := u.create.mutation.StartedAt(); exists { - s.SetIgnore(sandbox.FieldStartedAt) - } - })) - return u -} - -// Ignore sets each column to itself in case of conflict. -// Using this option is equivalent to using: -// -// client.Sandbox.Create(). -// OnConflict(sql.ResolveWithIgnore()). -// Exec(ctx) -func (u *SandboxUpsertOne) Ignore() *SandboxUpsertOne { - 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 *SandboxUpsertOne) DoNothing() *SandboxUpsertOne { - u.create.conflict = append(u.create.conflict, sql.DoNothing()) - return u -} - -// Update allows overriding fields `UPDATE` values. See the SandboxCreate.OnConflict -// documentation for more info. -func (u *SandboxUpsertOne) Update(set func(*SandboxUpsert)) *SandboxUpsertOne { - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { - set(&SandboxUpsert{UpdateSet: update}) - })) - return u -} - -// SetUpdatedAt sets the "updated_at" field. -func (u *SandboxUpsertOne) SetUpdatedAt(v time.Time) *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.SetUpdatedAt(v) - }) -} - -// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. -func (u *SandboxUpsertOne) UpdateUpdatedAt() *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.UpdateUpdatedAt() - }) -} - -// SetTerminatedAt sets the "terminated_at" field. -func (u *SandboxUpsertOne) SetTerminatedAt(v time.Time) *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.SetTerminatedAt(v) - }) -} - -// UpdateTerminatedAt sets the "terminated_at" field to the value that was provided on create. -func (u *SandboxUpsertOne) UpdateTerminatedAt() *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.UpdateTerminatedAt() - }) -} - -// SetDeadline sets the "deadline" field. -func (u *SandboxUpsertOne) SetDeadline(v time.Time) *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.SetDeadline(v) - }) -} - -// UpdateDeadline sets the "deadline" field to the value that was provided on create. -func (u *SandboxUpsertOne) UpdateDeadline() *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.UpdateDeadline() - }) -} - -// SetStatus sets the "status" field. -func (u *SandboxUpsertOne) SetStatus(v sandbox.Status) *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.SetStatus(v) - }) -} - -// UpdateStatus sets the "status" field to the value that was provided on create. -func (u *SandboxUpsertOne) UpdateStatus() *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.UpdateStatus() - }) -} - -// SetDurationMs sets the "duration_ms" field. -func (u *SandboxUpsertOne) SetDurationMs(v int64) *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.SetDurationMs(v) - }) -} - -// AddDurationMs adds v to the "duration_ms" field. -func (u *SandboxUpsertOne) AddDurationMs(v int64) *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.AddDurationMs(v) - }) -} - -// UpdateDurationMs sets the "duration_ms" field to the value that was provided on create. -func (u *SandboxUpsertOne) UpdateDurationMs() *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.UpdateDurationMs() - }) -} - -// SetVersion sets the "version" field. -func (u *SandboxUpsertOne) SetVersion(v int64) *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.SetVersion(v) - }) -} - -// AddVersion adds v to the "version" field. -func (u *SandboxUpsertOne) AddVersion(v int64) *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.AddVersion(v) - }) -} - -// UpdateVersion sets the "version" field to the value that was provided on create. -func (u *SandboxUpsertOne) UpdateVersion() *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.UpdateVersion() - }) -} - -// SetGlobalVersion sets the "global_version" field. -func (u *SandboxUpsertOne) SetGlobalVersion(v int64) *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.SetGlobalVersion(v) - }) -} - -// AddGlobalVersion adds v to the "global_version" field. -func (u *SandboxUpsertOne) AddGlobalVersion(v int64) *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.AddGlobalVersion(v) - }) -} - -// UpdateGlobalVersion sets the "global_version" field to the value that was provided on create. -func (u *SandboxUpsertOne) UpdateGlobalVersion() *SandboxUpsertOne { - return u.Update(func(s *SandboxUpsert) { - s.UpdateGlobalVersion() - }) -} - -// Exec executes the query. -func (u *SandboxUpsertOne) Exec(ctx context.Context) error { - if len(u.create.conflict) == 0 { - return errors.New("models: missing options for SandboxCreate.OnConflict") - } - return u.create.Exec(ctx) -} - -// ExecX is like Exec, but panics if an error occurs. -func (u *SandboxUpsertOne) 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 *SandboxUpsertOne) ID(ctx context.Context) (id string, err error) { - if u.create.driver.Dialect() == dialect.MySQL { - // In case of "ON CONFLICT", there is no way to get back non-numeric ID - // fields from the database since MySQL does not support the RETURNING clause. - return id, errors.New("models: SandboxUpsertOne.ID is not supported by MySQL driver. Use SandboxUpsertOne.Exec instead") - } - node, err := u.create.Save(ctx) - if err != nil { - return id, err - } - return node.ID, nil -} - -// IDX is like ID, but panics if an error occurs. -func (u *SandboxUpsertOne) IDX(ctx context.Context) string { - id, err := u.ID(ctx) - if err != nil { - panic(err) - } - return id -} - -// SandboxCreateBulk is the builder for creating many Sandbox entities in bulk. -type SandboxCreateBulk struct { - config - err error - builders []*SandboxCreate - conflict []sql.ConflictOption -} - -// Save creates the Sandbox entities in the database. -func (scb *SandboxCreateBulk) Save(ctx context.Context) ([]*Sandbox, error) { - if scb.err != nil { - return nil, scb.err - } - specs := make([]*sqlgraph.CreateSpec, len(scb.builders)) - nodes := make([]*Sandbox, len(scb.builders)) - mutators := make([]Mutator, len(scb.builders)) - for i := range scb.builders { - func(i int, root context.Context) { - builder := scb.builders[i] - builder.defaults() - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*SandboxMutation) - 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, scb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - spec.OnConflict = scb.conflict - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, scb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, scb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (scb *SandboxCreateBulk) SaveX(ctx context.Context) []*Sandbox { - v, err := scb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (scb *SandboxCreateBulk) Exec(ctx context.Context) error { - _, err := scb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (scb *SandboxCreateBulk) ExecX(ctx context.Context) { - if err := scb.Exec(ctx); err != nil { - panic(err) - } -} - -// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause -// of the `INSERT` statement. For example: -// -// client.Sandbox.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.SandboxUpsert) { -// SetStartedAt(v+v). -// }). -// Exec(ctx) -func (scb *SandboxCreateBulk) OnConflict(opts ...sql.ConflictOption) *SandboxUpsertBulk { - scb.conflict = opts - return &SandboxUpsertBulk{ - create: scb, - } -} - -// OnConflictColumns calls `OnConflict` and configures the columns -// as conflict target. Using this option is equivalent to using: -// -// client.Sandbox.Create(). -// OnConflict(sql.ConflictColumns(columns...)). -// Exec(ctx) -func (scb *SandboxCreateBulk) OnConflictColumns(columns ...string) *SandboxUpsertBulk { - scb.conflict = append(scb.conflict, sql.ConflictColumns(columns...)) - return &SandboxUpsertBulk{ - create: scb, - } -} - -// SandboxUpsertBulk is the builder for "upsert"-ing -// a bulk of Sandbox nodes. -type SandboxUpsertBulk struct { - create *SandboxCreateBulk -} - -// UpdateNewValues updates the mutable fields using the new values that -// were set on create. Using this option is equivalent to using: -// -// client.Sandbox.Create(). -// OnConflict( -// sql.ResolveWithNewValues(), -// sql.ResolveWith(func(u *sql.UpdateSet) { -// u.SetIgnore(sandbox.FieldID) -// }), -// ). -// Exec(ctx) -func (u *SandboxUpsertBulk) UpdateNewValues() *SandboxUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { - for _, b := range u.create.builders { - if _, exists := b.mutation.ID(); exists { - s.SetIgnore(sandbox.FieldID) - } - if _, exists := b.mutation.StartedAt(); exists { - s.SetIgnore(sandbox.FieldStartedAt) - } - } - })) - return u -} - -// Ignore sets each column to itself in case of conflict. -// Using this option is equivalent to using: -// -// client.Sandbox.Create(). -// OnConflict(sql.ResolveWithIgnore()). -// Exec(ctx) -func (u *SandboxUpsertBulk) Ignore() *SandboxUpsertBulk { - 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 *SandboxUpsertBulk) DoNothing() *SandboxUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.DoNothing()) - return u -} - -// Update allows overriding fields `UPDATE` values. See the SandboxCreateBulk.OnConflict -// documentation for more info. -func (u *SandboxUpsertBulk) Update(set func(*SandboxUpsert)) *SandboxUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { - set(&SandboxUpsert{UpdateSet: update}) - })) - return u -} - -// SetUpdatedAt sets the "updated_at" field. -func (u *SandboxUpsertBulk) SetUpdatedAt(v time.Time) *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.SetUpdatedAt(v) - }) -} - -// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. -func (u *SandboxUpsertBulk) UpdateUpdatedAt() *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.UpdateUpdatedAt() - }) -} - -// SetTerminatedAt sets the "terminated_at" field. -func (u *SandboxUpsertBulk) SetTerminatedAt(v time.Time) *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.SetTerminatedAt(v) - }) -} - -// UpdateTerminatedAt sets the "terminated_at" field to the value that was provided on create. -func (u *SandboxUpsertBulk) UpdateTerminatedAt() *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.UpdateTerminatedAt() - }) -} - -// SetDeadline sets the "deadline" field. -func (u *SandboxUpsertBulk) SetDeadline(v time.Time) *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.SetDeadline(v) - }) -} - -// UpdateDeadline sets the "deadline" field to the value that was provided on create. -func (u *SandboxUpsertBulk) UpdateDeadline() *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.UpdateDeadline() - }) -} - -// SetStatus sets the "status" field. -func (u *SandboxUpsertBulk) SetStatus(v sandbox.Status) *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.SetStatus(v) - }) -} - -// UpdateStatus sets the "status" field to the value that was provided on create. -func (u *SandboxUpsertBulk) UpdateStatus() *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.UpdateStatus() - }) -} - -// SetDurationMs sets the "duration_ms" field. -func (u *SandboxUpsertBulk) SetDurationMs(v int64) *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.SetDurationMs(v) - }) -} - -// AddDurationMs adds v to the "duration_ms" field. -func (u *SandboxUpsertBulk) AddDurationMs(v int64) *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.AddDurationMs(v) - }) -} - -// UpdateDurationMs sets the "duration_ms" field to the value that was provided on create. -func (u *SandboxUpsertBulk) UpdateDurationMs() *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.UpdateDurationMs() - }) -} - -// SetVersion sets the "version" field. -func (u *SandboxUpsertBulk) SetVersion(v int64) *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.SetVersion(v) - }) -} - -// AddVersion adds v to the "version" field. -func (u *SandboxUpsertBulk) AddVersion(v int64) *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.AddVersion(v) - }) -} - -// UpdateVersion sets the "version" field to the value that was provided on create. -func (u *SandboxUpsertBulk) UpdateVersion() *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.UpdateVersion() - }) -} - -// SetGlobalVersion sets the "global_version" field. -func (u *SandboxUpsertBulk) SetGlobalVersion(v int64) *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.SetGlobalVersion(v) - }) -} - -// AddGlobalVersion adds v to the "global_version" field. -func (u *SandboxUpsertBulk) AddGlobalVersion(v int64) *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.AddGlobalVersion(v) - }) -} - -// UpdateGlobalVersion sets the "global_version" field to the value that was provided on create. -func (u *SandboxUpsertBulk) UpdateGlobalVersion() *SandboxUpsertBulk { - return u.Update(func(s *SandboxUpsert) { - s.UpdateGlobalVersion() - }) -} - -// Exec executes the query. -func (u *SandboxUpsertBulk) Exec(ctx context.Context) error { - if u.create.err != nil { - return u.create.err - } - for i, b := range u.create.builders { - if len(b.conflict) != 0 { - return fmt.Errorf("models: OnConflict was set for builder %d. Set it on the SandboxCreateBulk instead", i) - } - } - if len(u.create.conflict) == 0 { - return errors.New("models: missing options for SandboxCreateBulk.OnConflict") - } - return u.create.Exec(ctx) -} - -// ExecX is like Exec, but panics if an error occurs. -func (u *SandboxUpsertBulk) ExecX(ctx context.Context) { - if err := u.create.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/packages/orchestrator/internal/pkg/models/sandbox_delete.go b/packages/orchestrator/internal/pkg/models/sandbox_delete.go deleted file mode 100644 index 375a71859..000000000 --- a/packages/orchestrator/internal/pkg/models/sandbox_delete.go +++ /dev/null @@ -1,91 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" -) - -// SandboxDelete is the builder for deleting a Sandbox entity. -type SandboxDelete struct { - config - hooks []Hook - mutation *SandboxMutation -} - -// Where appends a list predicates to the SandboxDelete builder. -func (sd *SandboxDelete) Where(ps ...predicate.Sandbox) *SandboxDelete { - sd.mutation.Where(ps...) - return sd -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (sd *SandboxDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, sd.sqlExec, sd.mutation, sd.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (sd *SandboxDelete) ExecX(ctx context.Context) int { - n, err := sd.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (sd *SandboxDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(sandbox.Table, sqlgraph.NewFieldSpec(sandbox.FieldID, field.TypeString)) - _spec.Node.Schema = sd.schemaConfig.Sandbox - ctx = internal.NewSchemaConfigContext(ctx, sd.schemaConfig) - if ps := sd.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, sd.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - sd.mutation.done = true - return affected, err -} - -// SandboxDeleteOne is the builder for deleting a single Sandbox entity. -type SandboxDeleteOne struct { - sd *SandboxDelete -} - -// Where appends a list predicates to the SandboxDelete builder. -func (sdo *SandboxDeleteOne) Where(ps ...predicate.Sandbox) *SandboxDeleteOne { - sdo.sd.mutation.Where(ps...) - return sdo -} - -// Exec executes the deletion query. -func (sdo *SandboxDeleteOne) Exec(ctx context.Context) error { - n, err := sdo.sd.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{sandbox.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (sdo *SandboxDeleteOne) ExecX(ctx context.Context) { - if err := sdo.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/packages/orchestrator/internal/pkg/models/sandbox_query.go b/packages/orchestrator/internal/pkg/models/sandbox_query.go deleted file mode 100644 index 8bd700649..000000000 --- a/packages/orchestrator/internal/pkg/models/sandbox_query.go +++ /dev/null @@ -1,556 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" -) - -// SandboxQuery is the builder for querying Sandbox entities. -type SandboxQuery struct { - config - ctx *QueryContext - order []sandbox.OrderOption - inters []Interceptor - predicates []predicate.Sandbox - 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 SandboxQuery builder. -func (sq *SandboxQuery) Where(ps ...predicate.Sandbox) *SandboxQuery { - sq.predicates = append(sq.predicates, ps...) - return sq -} - -// Limit the number of records to be returned by this query. -func (sq *SandboxQuery) Limit(limit int) *SandboxQuery { - sq.ctx.Limit = &limit - return sq -} - -// Offset to start from. -func (sq *SandboxQuery) Offset(offset int) *SandboxQuery { - sq.ctx.Offset = &offset - return sq -} - -// 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 (sq *SandboxQuery) Unique(unique bool) *SandboxQuery { - sq.ctx.Unique = &unique - return sq -} - -// Order specifies how the records should be ordered. -func (sq *SandboxQuery) Order(o ...sandbox.OrderOption) *SandboxQuery { - sq.order = append(sq.order, o...) - return sq -} - -// First returns the first Sandbox entity from the query. -// Returns a *NotFoundError when no Sandbox was found. -func (sq *SandboxQuery) First(ctx context.Context) (*Sandbox, error) { - nodes, err := sq.Limit(1).All(setContextOp(ctx, sq.ctx, "First")) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{sandbox.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (sq *SandboxQuery) FirstX(ctx context.Context) *Sandbox { - node, err := sq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first Sandbox ID from the query. -// Returns a *NotFoundError when no Sandbox ID was found. -func (sq *SandboxQuery) FirstID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = sq.Limit(1).IDs(setContextOp(ctx, sq.ctx, "FirstID")); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{sandbox.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (sq *SandboxQuery) FirstIDX(ctx context.Context) string { - id, err := sq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single Sandbox entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one Sandbox entity is found. -// Returns a *NotFoundError when no Sandbox entities are found. -func (sq *SandboxQuery) Only(ctx context.Context) (*Sandbox, error) { - nodes, err := sq.Limit(2).All(setContextOp(ctx, sq.ctx, "Only")) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{sandbox.Label} - default: - return nil, &NotSingularError{sandbox.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (sq *SandboxQuery) OnlyX(ctx context.Context) *Sandbox { - node, err := sq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only Sandbox ID in the query. -// Returns a *NotSingularError when more than one Sandbox ID is found. -// Returns a *NotFoundError when no entities are found. -func (sq *SandboxQuery) OnlyID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = sq.Limit(2).IDs(setContextOp(ctx, sq.ctx, "OnlyID")); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{sandbox.Label} - default: - err = &NotSingularError{sandbox.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (sq *SandboxQuery) OnlyIDX(ctx context.Context) string { - id, err := sq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of Sandboxes. -func (sq *SandboxQuery) All(ctx context.Context) ([]*Sandbox, error) { - ctx = setContextOp(ctx, sq.ctx, "All") - if err := sq.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*Sandbox, *SandboxQuery]() - return withInterceptors[[]*Sandbox](ctx, sq, qr, sq.inters) -} - -// AllX is like All, but panics if an error occurs. -func (sq *SandboxQuery) AllX(ctx context.Context) []*Sandbox { - nodes, err := sq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of Sandbox IDs. -func (sq *SandboxQuery) IDs(ctx context.Context) (ids []string, err error) { - if sq.ctx.Unique == nil && sq.path != nil { - sq.Unique(true) - } - ctx = setContextOp(ctx, sq.ctx, "IDs") - if err = sq.Select(sandbox.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (sq *SandboxQuery) IDsX(ctx context.Context) []string { - ids, err := sq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (sq *SandboxQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, sq.ctx, "Count") - if err := sq.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, sq, querierCount[*SandboxQuery](), sq.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (sq *SandboxQuery) CountX(ctx context.Context) int { - count, err := sq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (sq *SandboxQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, sq.ctx, "Exist") - switch _, err := sq.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("models: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (sq *SandboxQuery) ExistX(ctx context.Context) bool { - exist, err := sq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the SandboxQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (sq *SandboxQuery) Clone() *SandboxQuery { - if sq == nil { - return nil - } - return &SandboxQuery{ - config: sq.config, - ctx: sq.ctx.Clone(), - order: append([]sandbox.OrderOption{}, sq.order...), - inters: append([]Interceptor{}, sq.inters...), - predicates: append([]predicate.Sandbox{}, sq.predicates...), - // clone intermediate query. - sql: sq.sql.Clone(), - path: sq.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 { -// StartedAt time.Time `json:"started_at,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.Sandbox.Query(). -// GroupBy(sandbox.FieldStartedAt). -// Aggregate(models.Count()). -// Scan(ctx, &v) -func (sq *SandboxQuery) GroupBy(field string, fields ...string) *SandboxGroupBy { - sq.ctx.Fields = append([]string{field}, fields...) - grbuild := &SandboxGroupBy{build: sq} - grbuild.flds = &sq.ctx.Fields - grbuild.label = sandbox.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 { -// StartedAt time.Time `json:"started_at,omitempty"` -// } -// -// client.Sandbox.Query(). -// Select(sandbox.FieldStartedAt). -// Scan(ctx, &v) -func (sq *SandboxQuery) Select(fields ...string) *SandboxSelect { - sq.ctx.Fields = append(sq.ctx.Fields, fields...) - sbuild := &SandboxSelect{SandboxQuery: sq} - sbuild.label = sandbox.Label - sbuild.flds, sbuild.scan = &sq.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a SandboxSelect configured with the given aggregations. -func (sq *SandboxQuery) Aggregate(fns ...AggregateFunc) *SandboxSelect { - return sq.Select().Aggregate(fns...) -} - -func (sq *SandboxQuery) prepareQuery(ctx context.Context) error { - for _, inter := range sq.inters { - if inter == nil { - return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, sq); err != nil { - return err - } - } - } - for _, f := range sq.ctx.Fields { - if !sandbox.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} - } - } - if sq.path != nil { - prev, err := sq.path(ctx) - if err != nil { - return err - } - sq.sql = prev - } - return nil -} - -func (sq *SandboxQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Sandbox, error) { - var ( - nodes = []*Sandbox{} - _spec = sq.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*Sandbox).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &Sandbox{config: sq.config} - nodes = append(nodes, node) - return node.assignValues(columns, values) - } - _spec.Node.Schema = sq.schemaConfig.Sandbox - ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) - if len(sq.modifiers) > 0 { - _spec.Modifiers = sq.modifiers - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, sq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (sq *SandboxQuery) sqlCount(ctx context.Context) (int, error) { - _spec := sq.querySpec() - _spec.Node.Schema = sq.schemaConfig.Sandbox - ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) - if len(sq.modifiers) > 0 { - _spec.Modifiers = sq.modifiers - } - _spec.Node.Columns = sq.ctx.Fields - if len(sq.ctx.Fields) > 0 { - _spec.Unique = sq.ctx.Unique != nil && *sq.ctx.Unique - } - return sqlgraph.CountNodes(ctx, sq.driver, _spec) -} - -func (sq *SandboxQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(sandbox.Table, sandbox.Columns, sqlgraph.NewFieldSpec(sandbox.FieldID, field.TypeString)) - _spec.From = sq.sql - if unique := sq.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if sq.path != nil { - _spec.Unique = true - } - if fields := sq.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, sandbox.FieldID) - for i := range fields { - if fields[i] != sandbox.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := sq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := sq.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := sq.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := sq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (sq *SandboxQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(sq.driver.Dialect()) - t1 := builder.Table(sandbox.Table) - columns := sq.ctx.Fields - if len(columns) == 0 { - columns = sandbox.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if sq.sql != nil { - selector = sq.sql - selector.Select(selector.Columns(columns...)...) - } - if sq.ctx.Unique != nil && *sq.ctx.Unique { - selector.Distinct() - } - t1.Schema(sq.schemaConfig.Sandbox) - ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) - selector.WithContext(ctx) - for _, m := range sq.modifiers { - m(selector) - } - for _, p := range sq.predicates { - p(selector) - } - for _, p := range sq.order { - p(selector) - } - if offset := sq.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 := sq.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// Modify adds a query modifier for attaching custom logic to queries. -func (sq *SandboxQuery) Modify(modifiers ...func(s *sql.Selector)) *SandboxSelect { - sq.modifiers = append(sq.modifiers, modifiers...) - return sq.Select() -} - -// SandboxGroupBy is the group-by builder for Sandbox entities. -type SandboxGroupBy struct { - selector - build *SandboxQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (sgb *SandboxGroupBy) Aggregate(fns ...AggregateFunc) *SandboxGroupBy { - sgb.fns = append(sgb.fns, fns...) - return sgb -} - -// Scan applies the selector query and scans the result into the given value. -func (sgb *SandboxGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, sgb.build.ctx, "GroupBy") - if err := sgb.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*SandboxQuery, *SandboxGroupBy](ctx, sgb.build, sgb, sgb.build.inters, v) -} - -func (sgb *SandboxGroupBy) sqlScan(ctx context.Context, root *SandboxQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(sgb.fns)) - for _, fn := range sgb.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*sgb.flds)+len(sgb.fns)) - for _, f := range *sgb.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*sgb.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := sgb.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// SandboxSelect is the builder for selecting fields of Sandbox entities. -type SandboxSelect struct { - *SandboxQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (ss *SandboxSelect) Aggregate(fns ...AggregateFunc) *SandboxSelect { - ss.fns = append(ss.fns, fns...) - return ss -} - -// Scan applies the selector query and scans the result into the given value. -func (ss *SandboxSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, ss.ctx, "Select") - if err := ss.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*SandboxQuery, *SandboxSelect](ctx, ss.SandboxQuery, ss, ss.inters, v) -} - -func (ss *SandboxSelect) sqlScan(ctx context.Context, root *SandboxQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(ss.fns)) - for _, fn := range ss.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*ss.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 := ss.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// Modify adds a query modifier for attaching custom logic to queries. -func (ss *SandboxSelect) Modify(modifiers ...func(s *sql.Selector)) *SandboxSelect { - ss.modifiers = append(ss.modifiers, modifiers...) - return ss -} diff --git a/packages/orchestrator/internal/pkg/models/sandbox_update.go b/packages/orchestrator/internal/pkg/models/sandbox_update.go deleted file mode 100644 index 3b9dd987e..000000000 --- a/packages/orchestrator/internal/pkg/models/sandbox_update.go +++ /dev/null @@ -1,551 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" -) - -// SandboxUpdate is the builder for updating Sandbox entities. -type SandboxUpdate struct { - config - hooks []Hook - mutation *SandboxMutation - modifiers []func(*sql.UpdateBuilder) -} - -// Where appends a list predicates to the SandboxUpdate builder. -func (su *SandboxUpdate) Where(ps ...predicate.Sandbox) *SandboxUpdate { - su.mutation.Where(ps...) - return su -} - -// SetUpdatedAt sets the "updated_at" field. -func (su *SandboxUpdate) SetUpdatedAt(t time.Time) *SandboxUpdate { - su.mutation.SetUpdatedAt(t) - return su -} - -// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. -func (su *SandboxUpdate) SetNillableUpdatedAt(t *time.Time) *SandboxUpdate { - if t != nil { - su.SetUpdatedAt(*t) - } - return su -} - -// SetTerminatedAt sets the "terminated_at" field. -func (su *SandboxUpdate) SetTerminatedAt(t time.Time) *SandboxUpdate { - su.mutation.SetTerminatedAt(t) - return su -} - -// SetNillableTerminatedAt sets the "terminated_at" field if the given value is not nil. -func (su *SandboxUpdate) SetNillableTerminatedAt(t *time.Time) *SandboxUpdate { - if t != nil { - su.SetTerminatedAt(*t) - } - return su -} - -// SetDeadline sets the "deadline" field. -func (su *SandboxUpdate) SetDeadline(t time.Time) *SandboxUpdate { - su.mutation.SetDeadline(t) - return su -} - -// SetNillableDeadline sets the "deadline" field if the given value is not nil. -func (su *SandboxUpdate) SetNillableDeadline(t *time.Time) *SandboxUpdate { - if t != nil { - su.SetDeadline(*t) - } - return su -} - -// SetStatus sets the "status" field. -func (su *SandboxUpdate) SetStatus(s sandbox.Status) *SandboxUpdate { - su.mutation.SetStatus(s) - return su -} - -// SetNillableStatus sets the "status" field if the given value is not nil. -func (su *SandboxUpdate) SetNillableStatus(s *sandbox.Status) *SandboxUpdate { - if s != nil { - su.SetStatus(*s) - } - return su -} - -// SetDurationMs sets the "duration_ms" field. -func (su *SandboxUpdate) SetDurationMs(i int64) *SandboxUpdate { - su.mutation.ResetDurationMs() - su.mutation.SetDurationMs(i) - return su -} - -// SetNillableDurationMs sets the "duration_ms" field if the given value is not nil. -func (su *SandboxUpdate) SetNillableDurationMs(i *int64) *SandboxUpdate { - if i != nil { - su.SetDurationMs(*i) - } - return su -} - -// AddDurationMs adds i to the "duration_ms" field. -func (su *SandboxUpdate) AddDurationMs(i int64) *SandboxUpdate { - su.mutation.AddDurationMs(i) - return su -} - -// SetVersion sets the "version" field. -func (su *SandboxUpdate) SetVersion(i int64) *SandboxUpdate { - su.mutation.ResetVersion() - su.mutation.SetVersion(i) - return su -} - -// SetNillableVersion sets the "version" field if the given value is not nil. -func (su *SandboxUpdate) SetNillableVersion(i *int64) *SandboxUpdate { - if i != nil { - su.SetVersion(*i) - } - return su -} - -// AddVersion adds i to the "version" field. -func (su *SandboxUpdate) AddVersion(i int64) *SandboxUpdate { - su.mutation.AddVersion(i) - return su -} - -// SetGlobalVersion sets the "global_version" field. -func (su *SandboxUpdate) SetGlobalVersion(i int64) *SandboxUpdate { - su.mutation.ResetGlobalVersion() - su.mutation.SetGlobalVersion(i) - return su -} - -// SetNillableGlobalVersion sets the "global_version" field if the given value is not nil. -func (su *SandboxUpdate) SetNillableGlobalVersion(i *int64) *SandboxUpdate { - if i != nil { - su.SetGlobalVersion(*i) - } - return su -} - -// AddGlobalVersion adds i to the "global_version" field. -func (su *SandboxUpdate) AddGlobalVersion(i int64) *SandboxUpdate { - su.mutation.AddGlobalVersion(i) - return su -} - -// Mutation returns the SandboxMutation object of the builder. -func (su *SandboxUpdate) Mutation() *SandboxMutation { - return su.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (su *SandboxUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, su.sqlSave, su.mutation, su.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (su *SandboxUpdate) SaveX(ctx context.Context) int { - affected, err := su.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (su *SandboxUpdate) Exec(ctx context.Context) error { - _, err := su.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (su *SandboxUpdate) ExecX(ctx context.Context) { - if err := su.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (su *SandboxUpdate) check() error { - if v, ok := su.mutation.Status(); ok { - if err := sandbox.StatusValidator(v); err != nil { - return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Sandbox.status": %w`, err)} - } - } - if v, ok := su.mutation.DurationMs(); ok { - if err := sandbox.DurationMsValidator(v); err != nil { - return &ValidationError{Name: "duration_ms", err: fmt.Errorf(`models: validator failed for field "Sandbox.duration_ms": %w`, err)} - } - } - if v, ok := su.mutation.Version(); ok { - if err := sandbox.VersionValidator(v); err != nil { - return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Sandbox.version": %w`, err)} - } - } - if v, ok := su.mutation.GlobalVersion(); ok { - if err := sandbox.GlobalVersionValidator(v); err != nil { - return &ValidationError{Name: "global_version", err: fmt.Errorf(`models: validator failed for field "Sandbox.global_version": %w`, err)} - } - } - return nil -} - -// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. -func (su *SandboxUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SandboxUpdate { - su.modifiers = append(su.modifiers, modifiers...) - return su -} - -func (su *SandboxUpdate) sqlSave(ctx context.Context) (n int, err error) { - if err := su.check(); err != nil { - return n, err - } - _spec := sqlgraph.NewUpdateSpec(sandbox.Table, sandbox.Columns, sqlgraph.NewFieldSpec(sandbox.FieldID, field.TypeString)) - if ps := su.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := su.mutation.UpdatedAt(); ok { - _spec.SetField(sandbox.FieldUpdatedAt, field.TypeTime, value) - } - if value, ok := su.mutation.TerminatedAt(); ok { - _spec.SetField(sandbox.FieldTerminatedAt, field.TypeTime, value) - } - if value, ok := su.mutation.Deadline(); ok { - _spec.SetField(sandbox.FieldDeadline, field.TypeTime, value) - } - if value, ok := su.mutation.Status(); ok { - _spec.SetField(sandbox.FieldStatus, field.TypeEnum, value) - } - if value, ok := su.mutation.DurationMs(); ok { - _spec.SetField(sandbox.FieldDurationMs, field.TypeInt64, value) - } - if value, ok := su.mutation.AddedDurationMs(); ok { - _spec.AddField(sandbox.FieldDurationMs, field.TypeInt64, value) - } - if value, ok := su.mutation.Version(); ok { - _spec.SetField(sandbox.FieldVersion, field.TypeInt64, value) - } - if value, ok := su.mutation.AddedVersion(); ok { - _spec.AddField(sandbox.FieldVersion, field.TypeInt64, value) - } - if value, ok := su.mutation.GlobalVersion(); ok { - _spec.SetField(sandbox.FieldGlobalVersion, field.TypeInt64, value) - } - if value, ok := su.mutation.AddedGlobalVersion(); ok { - _spec.AddField(sandbox.FieldGlobalVersion, field.TypeInt64, value) - } - _spec.Node.Schema = su.schemaConfig.Sandbox - ctx = internal.NewSchemaConfigContext(ctx, su.schemaConfig) - _spec.AddModifiers(su.modifiers...) - if n, err = sqlgraph.UpdateNodes(ctx, su.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{sandbox.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - su.mutation.done = true - return n, nil -} - -// SandboxUpdateOne is the builder for updating a single Sandbox entity. -type SandboxUpdateOne struct { - config - fields []string - hooks []Hook - mutation *SandboxMutation - modifiers []func(*sql.UpdateBuilder) -} - -// SetUpdatedAt sets the "updated_at" field. -func (suo *SandboxUpdateOne) SetUpdatedAt(t time.Time) *SandboxUpdateOne { - suo.mutation.SetUpdatedAt(t) - return suo -} - -// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. -func (suo *SandboxUpdateOne) SetNillableUpdatedAt(t *time.Time) *SandboxUpdateOne { - if t != nil { - suo.SetUpdatedAt(*t) - } - return suo -} - -// SetTerminatedAt sets the "terminated_at" field. -func (suo *SandboxUpdateOne) SetTerminatedAt(t time.Time) *SandboxUpdateOne { - suo.mutation.SetTerminatedAt(t) - return suo -} - -// SetNillableTerminatedAt sets the "terminated_at" field if the given value is not nil. -func (suo *SandboxUpdateOne) SetNillableTerminatedAt(t *time.Time) *SandboxUpdateOne { - if t != nil { - suo.SetTerminatedAt(*t) - } - return suo -} - -// SetDeadline sets the "deadline" field. -func (suo *SandboxUpdateOne) SetDeadline(t time.Time) *SandboxUpdateOne { - suo.mutation.SetDeadline(t) - return suo -} - -// SetNillableDeadline sets the "deadline" field if the given value is not nil. -func (suo *SandboxUpdateOne) SetNillableDeadline(t *time.Time) *SandboxUpdateOne { - if t != nil { - suo.SetDeadline(*t) - } - return suo -} - -// SetStatus sets the "status" field. -func (suo *SandboxUpdateOne) SetStatus(s sandbox.Status) *SandboxUpdateOne { - suo.mutation.SetStatus(s) - return suo -} - -// SetNillableStatus sets the "status" field if the given value is not nil. -func (suo *SandboxUpdateOne) SetNillableStatus(s *sandbox.Status) *SandboxUpdateOne { - if s != nil { - suo.SetStatus(*s) - } - return suo -} - -// SetDurationMs sets the "duration_ms" field. -func (suo *SandboxUpdateOne) SetDurationMs(i int64) *SandboxUpdateOne { - suo.mutation.ResetDurationMs() - suo.mutation.SetDurationMs(i) - return suo -} - -// SetNillableDurationMs sets the "duration_ms" field if the given value is not nil. -func (suo *SandboxUpdateOne) SetNillableDurationMs(i *int64) *SandboxUpdateOne { - if i != nil { - suo.SetDurationMs(*i) - } - return suo -} - -// AddDurationMs adds i to the "duration_ms" field. -func (suo *SandboxUpdateOne) AddDurationMs(i int64) *SandboxUpdateOne { - suo.mutation.AddDurationMs(i) - return suo -} - -// SetVersion sets the "version" field. -func (suo *SandboxUpdateOne) SetVersion(i int64) *SandboxUpdateOne { - suo.mutation.ResetVersion() - suo.mutation.SetVersion(i) - return suo -} - -// SetNillableVersion sets the "version" field if the given value is not nil. -func (suo *SandboxUpdateOne) SetNillableVersion(i *int64) *SandboxUpdateOne { - if i != nil { - suo.SetVersion(*i) - } - return suo -} - -// AddVersion adds i to the "version" field. -func (suo *SandboxUpdateOne) AddVersion(i int64) *SandboxUpdateOne { - suo.mutation.AddVersion(i) - return suo -} - -// SetGlobalVersion sets the "global_version" field. -func (suo *SandboxUpdateOne) SetGlobalVersion(i int64) *SandboxUpdateOne { - suo.mutation.ResetGlobalVersion() - suo.mutation.SetGlobalVersion(i) - return suo -} - -// SetNillableGlobalVersion sets the "global_version" field if the given value is not nil. -func (suo *SandboxUpdateOne) SetNillableGlobalVersion(i *int64) *SandboxUpdateOne { - if i != nil { - suo.SetGlobalVersion(*i) - } - return suo -} - -// AddGlobalVersion adds i to the "global_version" field. -func (suo *SandboxUpdateOne) AddGlobalVersion(i int64) *SandboxUpdateOne { - suo.mutation.AddGlobalVersion(i) - return suo -} - -// Mutation returns the SandboxMutation object of the builder. -func (suo *SandboxUpdateOne) Mutation() *SandboxMutation { - return suo.mutation -} - -// Where appends a list predicates to the SandboxUpdate builder. -func (suo *SandboxUpdateOne) Where(ps ...predicate.Sandbox) *SandboxUpdateOne { - suo.mutation.Where(ps...) - return suo -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (suo *SandboxUpdateOne) Select(field string, fields ...string) *SandboxUpdateOne { - suo.fields = append([]string{field}, fields...) - return suo -} - -// Save executes the query and returns the updated Sandbox entity. -func (suo *SandboxUpdateOne) Save(ctx context.Context) (*Sandbox, error) { - return withHooks(ctx, suo.sqlSave, suo.mutation, suo.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (suo *SandboxUpdateOne) SaveX(ctx context.Context) *Sandbox { - node, err := suo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (suo *SandboxUpdateOne) Exec(ctx context.Context) error { - _, err := suo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (suo *SandboxUpdateOne) ExecX(ctx context.Context) { - if err := suo.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (suo *SandboxUpdateOne) check() error { - if v, ok := suo.mutation.Status(); ok { - if err := sandbox.StatusValidator(v); err != nil { - return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Sandbox.status": %w`, err)} - } - } - if v, ok := suo.mutation.DurationMs(); ok { - if err := sandbox.DurationMsValidator(v); err != nil { - return &ValidationError{Name: "duration_ms", err: fmt.Errorf(`models: validator failed for field "Sandbox.duration_ms": %w`, err)} - } - } - if v, ok := suo.mutation.Version(); ok { - if err := sandbox.VersionValidator(v); err != nil { - return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Sandbox.version": %w`, err)} - } - } - if v, ok := suo.mutation.GlobalVersion(); ok { - if err := sandbox.GlobalVersionValidator(v); err != nil { - return &ValidationError{Name: "global_version", err: fmt.Errorf(`models: validator failed for field "Sandbox.global_version": %w`, err)} - } - } - return nil -} - -// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. -func (suo *SandboxUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SandboxUpdateOne { - suo.modifiers = append(suo.modifiers, modifiers...) - return suo -} - -func (suo *SandboxUpdateOne) sqlSave(ctx context.Context) (_node *Sandbox, err error) { - if err := suo.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(sandbox.Table, sandbox.Columns, sqlgraph.NewFieldSpec(sandbox.FieldID, field.TypeString)) - id, ok := suo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Sandbox.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := suo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, sandbox.FieldID) - for _, f := range fields { - if !sandbox.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} - } - if f != sandbox.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := suo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := suo.mutation.UpdatedAt(); ok { - _spec.SetField(sandbox.FieldUpdatedAt, field.TypeTime, value) - } - if value, ok := suo.mutation.TerminatedAt(); ok { - _spec.SetField(sandbox.FieldTerminatedAt, field.TypeTime, value) - } - if value, ok := suo.mutation.Deadline(); ok { - _spec.SetField(sandbox.FieldDeadline, field.TypeTime, value) - } - if value, ok := suo.mutation.Status(); ok { - _spec.SetField(sandbox.FieldStatus, field.TypeEnum, value) - } - if value, ok := suo.mutation.DurationMs(); ok { - _spec.SetField(sandbox.FieldDurationMs, field.TypeInt64, value) - } - if value, ok := suo.mutation.AddedDurationMs(); ok { - _spec.AddField(sandbox.FieldDurationMs, field.TypeInt64, value) - } - if value, ok := suo.mutation.Version(); ok { - _spec.SetField(sandbox.FieldVersion, field.TypeInt64, value) - } - if value, ok := suo.mutation.AddedVersion(); ok { - _spec.AddField(sandbox.FieldVersion, field.TypeInt64, value) - } - if value, ok := suo.mutation.GlobalVersion(); ok { - _spec.SetField(sandbox.FieldGlobalVersion, field.TypeInt64, value) - } - if value, ok := suo.mutation.AddedGlobalVersion(); ok { - _spec.AddField(sandbox.FieldGlobalVersion, field.TypeInt64, value) - } - _spec.Node.Schema = suo.schemaConfig.Sandbox - ctx = internal.NewSchemaConfigContext(ctx, suo.schemaConfig) - _spec.AddModifiers(suo.modifiers...) - _node = &Sandbox{config: suo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, suo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{sandbox.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - suo.mutation.done = true - return _node, nil -} diff --git a/packages/orchestrator/internal/pkg/models/status.go b/packages/orchestrator/internal/pkg/models/status.go deleted file mode 100644 index 42160fb28..000000000 --- a/packages/orchestrator/internal/pkg/models/status.go +++ /dev/null @@ -1,128 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "fmt" - "strings" - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" -) - -// Status is the model entity for the Status schema. -type Status struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // Version holds the value of the "version" field. - Version int64 `json:"version,omitempty"` - // UpdatedAt holds the value of the "updated_at" field. - UpdatedAt time.Time `json:"updated_at,omitempty"` - // Status holds the value of the "status" field. - Status status.Status `json:"status,omitempty"` - selectValues sql.SelectValues -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*Status) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case status.FieldID, status.FieldVersion: - values[i] = new(sql.NullInt64) - case status.FieldStatus: - values[i] = new(sql.NullString) - case status.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 Status fields. -func (s *Status) 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 status.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - s.ID = int(value.Int64) - case status.FieldVersion: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field version", values[i]) - } else if value.Valid { - s.Version = value.Int64 - } - case status.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 { - s.UpdatedAt = value.Time - } - case status.FieldStatus: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field status", values[i]) - } else if value.Valid { - s.Status = status.Status(value.String) - } - default: - s.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the Status. -// This includes values selected through modifiers, order, etc. -func (s *Status) Value(name string) (ent.Value, error) { - return s.selectValues.Get(name) -} - -// Update returns a builder for updating this Status. -// Note that you need to call Status.Unwrap() before calling this method if this Status -// was returned from a transaction, and the transaction was committed or rolled back. -func (s *Status) Update() *StatusUpdateOne { - return NewStatusClient(s.config).UpdateOne(s) -} - -// Unwrap unwraps the Status 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 (s *Status) Unwrap() *Status { - _tx, ok := s.config.driver.(*txDriver) - if !ok { - panic("models: Status is not a transactional entity") - } - s.config.driver = _tx.drv - return s -} - -// String implements the fmt.Stringer. -func (s *Status) String() string { - var builder strings.Builder - builder.WriteString("Status(") - builder.WriteString(fmt.Sprintf("id=%v, ", s.ID)) - builder.WriteString("version=") - builder.WriteString(fmt.Sprintf("%v", s.Version)) - builder.WriteString(", ") - builder.WriteString("updated_at=") - builder.WriteString(s.UpdatedAt.Format(time.ANSIC)) - builder.WriteString(", ") - builder.WriteString("status=") - builder.WriteString(fmt.Sprintf("%v", s.Status)) - builder.WriteByte(')') - return builder.String() -} - -// StatusSlice is a parsable slice of Status. -type StatusSlice []*Status diff --git a/packages/orchestrator/internal/pkg/models/status/status.go b/packages/orchestrator/internal/pkg/models/status/status.go deleted file mode 100644 index 77f3425c8..000000000 --- a/packages/orchestrator/internal/pkg/models/status/status.go +++ /dev/null @@ -1,101 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package status - -import ( - "fmt" - "time" - - "entgo.io/ent/dialect/sql" -) - -const ( - // Label holds the string label denoting the status type in the database. - Label = "status" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldVersion holds the string denoting the version field in the database. - FieldVersion = "version" - // FieldUpdatedAt holds the string denoting the updated_at field in the database. - FieldUpdatedAt = "updated_at" - // FieldStatus holds the string denoting the status field in the database. - FieldStatus = "status" - // Table holds the table name of the status in the database. - Table = "status" -) - -// Columns holds all SQL columns for status fields. -var Columns = []string{ - FieldID, - FieldVersion, - FieldUpdatedAt, - FieldStatus, -} - -// 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 ( - // VersionValidator is a validator for the "version" field. It is called by the builders before save. - VersionValidator func(int64) error - // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. - DefaultUpdatedAt func() time.Time -) - -// Status defines the type for the "status" enum field. -type Status string - -// StatusRunning is the default value of the Status enum. -const DefaultStatus = StatusRunning - -// Status values. -const ( - StatusInitializing Status = "initializing" - StatusRunning Status = "running" - StatusDraining Status = "draining" - StatusTerminating Status = "terminating" -) - -func (s Status) String() string { - return string(s) -} - -// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. -func StatusValidator(s Status) error { - switch s { - case StatusInitializing, StatusRunning, StatusDraining, StatusTerminating: - return nil - default: - return fmt.Errorf("status: invalid enum value for status field: %q", s) - } -} - -// OrderOption defines the ordering options for the Status 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() -} - -// ByVersion orders the results by the version field. -func ByVersion(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldVersion, opts...).ToFunc() -} - -// ByUpdatedAt orders the results by the updated_at field. -func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() -} - -// ByStatus orders the results by the status field. -func ByStatus(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldStatus, opts...).ToFunc() -} diff --git a/packages/orchestrator/internal/pkg/models/status/where.go b/packages/orchestrator/internal/pkg/models/status/where.go deleted file mode 100644 index 6b6895deb..000000000 --- a/packages/orchestrator/internal/pkg/models/status/where.go +++ /dev/null @@ -1,180 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package status - -import ( - "time" - - "entgo.io/ent/dialect/sql" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.Status { - return predicate.Status(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.Status { - return predicate.Status(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.Status { - return predicate.Status(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.Status { - return predicate.Status(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.Status { - return predicate.Status(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.Status { - return predicate.Status(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.Status { - return predicate.Status(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.Status { - return predicate.Status(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.Status { - return predicate.Status(sql.FieldLTE(FieldID, id)) -} - -// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. -func Version(v int64) predicate.Status { - return predicate.Status(sql.FieldEQ(FieldVersion, v)) -} - -// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. -func UpdatedAt(v time.Time) predicate.Status { - return predicate.Status(sql.FieldEQ(FieldUpdatedAt, v)) -} - -// VersionEQ applies the EQ predicate on the "version" field. -func VersionEQ(v int64) predicate.Status { - return predicate.Status(sql.FieldEQ(FieldVersion, v)) -} - -// VersionNEQ applies the NEQ predicate on the "version" field. -func VersionNEQ(v int64) predicate.Status { - return predicate.Status(sql.FieldNEQ(FieldVersion, v)) -} - -// VersionIn applies the In predicate on the "version" field. -func VersionIn(vs ...int64) predicate.Status { - return predicate.Status(sql.FieldIn(FieldVersion, vs...)) -} - -// VersionNotIn applies the NotIn predicate on the "version" field. -func VersionNotIn(vs ...int64) predicate.Status { - return predicate.Status(sql.FieldNotIn(FieldVersion, vs...)) -} - -// VersionGT applies the GT predicate on the "version" field. -func VersionGT(v int64) predicate.Status { - return predicate.Status(sql.FieldGT(FieldVersion, v)) -} - -// VersionGTE applies the GTE predicate on the "version" field. -func VersionGTE(v int64) predicate.Status { - return predicate.Status(sql.FieldGTE(FieldVersion, v)) -} - -// VersionLT applies the LT predicate on the "version" field. -func VersionLT(v int64) predicate.Status { - return predicate.Status(sql.FieldLT(FieldVersion, v)) -} - -// VersionLTE applies the LTE predicate on the "version" field. -func VersionLTE(v int64) predicate.Status { - return predicate.Status(sql.FieldLTE(FieldVersion, v)) -} - -// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. -func UpdatedAtEQ(v time.Time) predicate.Status { - return predicate.Status(sql.FieldEQ(FieldUpdatedAt, v)) -} - -// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. -func UpdatedAtNEQ(v time.Time) predicate.Status { - return predicate.Status(sql.FieldNEQ(FieldUpdatedAt, v)) -} - -// UpdatedAtIn applies the In predicate on the "updated_at" field. -func UpdatedAtIn(vs ...time.Time) predicate.Status { - return predicate.Status(sql.FieldIn(FieldUpdatedAt, vs...)) -} - -// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. -func UpdatedAtNotIn(vs ...time.Time) predicate.Status { - return predicate.Status(sql.FieldNotIn(FieldUpdatedAt, vs...)) -} - -// UpdatedAtGT applies the GT predicate on the "updated_at" field. -func UpdatedAtGT(v time.Time) predicate.Status { - return predicate.Status(sql.FieldGT(FieldUpdatedAt, v)) -} - -// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. -func UpdatedAtGTE(v time.Time) predicate.Status { - return predicate.Status(sql.FieldGTE(FieldUpdatedAt, v)) -} - -// UpdatedAtLT applies the LT predicate on the "updated_at" field. -func UpdatedAtLT(v time.Time) predicate.Status { - return predicate.Status(sql.FieldLT(FieldUpdatedAt, v)) -} - -// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. -func UpdatedAtLTE(v time.Time) predicate.Status { - return predicate.Status(sql.FieldLTE(FieldUpdatedAt, v)) -} - -// StatusEQ applies the EQ predicate on the "status" field. -func StatusEQ(v Status) predicate.Status { - return predicate.Status(sql.FieldEQ(FieldStatus, v)) -} - -// StatusNEQ applies the NEQ predicate on the "status" field. -func StatusNEQ(v Status) predicate.Status { - return predicate.Status(sql.FieldNEQ(FieldStatus, v)) -} - -// StatusIn applies the In predicate on the "status" field. -func StatusIn(vs ...Status) predicate.Status { - return predicate.Status(sql.FieldIn(FieldStatus, vs...)) -} - -// StatusNotIn applies the NotIn predicate on the "status" field. -func StatusNotIn(vs ...Status) predicate.Status { - return predicate.Status(sql.FieldNotIn(FieldStatus, vs...)) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.Status) predicate.Status { - return predicate.Status(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.Status) predicate.Status { - return predicate.Status(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.Status) predicate.Status { - return predicate.Status(sql.NotPredicates(p)) -} diff --git a/packages/orchestrator/internal/pkg/models/status_create.go b/packages/orchestrator/internal/pkg/models/status_create.go deleted file mode 100644 index 4a95a4ec0..000000000 --- a/packages/orchestrator/internal/pkg/models/status_create.go +++ /dev/null @@ -1,622 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" -) - -// StatusCreate is the builder for creating a Status entity. -type StatusCreate struct { - config - mutation *StatusMutation - hooks []Hook - conflict []sql.ConflictOption -} - -// SetVersion sets the "version" field. -func (sc *StatusCreate) SetVersion(i int64) *StatusCreate { - sc.mutation.SetVersion(i) - return sc -} - -// SetUpdatedAt sets the "updated_at" field. -func (sc *StatusCreate) SetUpdatedAt(t time.Time) *StatusCreate { - sc.mutation.SetUpdatedAt(t) - return sc -} - -// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. -func (sc *StatusCreate) SetNillableUpdatedAt(t *time.Time) *StatusCreate { - if t != nil { - sc.SetUpdatedAt(*t) - } - return sc -} - -// SetStatus sets the "status" field. -func (sc *StatusCreate) SetStatus(s status.Status) *StatusCreate { - sc.mutation.SetStatus(s) - return sc -} - -// SetNillableStatus sets the "status" field if the given value is not nil. -func (sc *StatusCreate) SetNillableStatus(s *status.Status) *StatusCreate { - if s != nil { - sc.SetStatus(*s) - } - return sc -} - -// Mutation returns the StatusMutation object of the builder. -func (sc *StatusCreate) Mutation() *StatusMutation { - return sc.mutation -} - -// Save creates the Status in the database. -func (sc *StatusCreate) Save(ctx context.Context) (*Status, error) { - sc.defaults() - return withHooks(ctx, sc.sqlSave, sc.mutation, sc.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (sc *StatusCreate) SaveX(ctx context.Context) *Status { - v, err := sc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (sc *StatusCreate) Exec(ctx context.Context) error { - _, err := sc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (sc *StatusCreate) ExecX(ctx context.Context) { - if err := sc.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (sc *StatusCreate) defaults() { - if _, ok := sc.mutation.UpdatedAt(); !ok { - v := status.DefaultUpdatedAt() - sc.mutation.SetUpdatedAt(v) - } - if _, ok := sc.mutation.Status(); !ok { - v := status.DefaultStatus - sc.mutation.SetStatus(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (sc *StatusCreate) check() error { - if _, ok := sc.mutation.Version(); !ok { - return &ValidationError{Name: "version", err: errors.New(`models: missing required field "Status.version"`)} - } - if v, ok := sc.mutation.Version(); ok { - if err := status.VersionValidator(v); err != nil { - return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Status.version": %w`, err)} - } - } - if _, ok := sc.mutation.UpdatedAt(); !ok { - return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Status.updated_at"`)} - } - if _, ok := sc.mutation.Status(); !ok { - return &ValidationError{Name: "status", err: errors.New(`models: missing required field "Status.status"`)} - } - if v, ok := sc.mutation.Status(); ok { - if err := status.StatusValidator(v); err != nil { - return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Status.status": %w`, err)} - } - } - return nil -} - -func (sc *StatusCreate) sqlSave(ctx context.Context) (*Status, error) { - if err := sc.check(); err != nil { - return nil, err - } - _node, _spec := sc.createSpec() - if err := sqlgraph.CreateNode(ctx, sc.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 = int(id) - sc.mutation.id = &_node.ID - sc.mutation.done = true - return _node, nil -} - -func (sc *StatusCreate) createSpec() (*Status, *sqlgraph.CreateSpec) { - var ( - _node = &Status{config: sc.config} - _spec = sqlgraph.NewCreateSpec(status.Table, sqlgraph.NewFieldSpec(status.FieldID, field.TypeInt)) - ) - _spec.Schema = sc.schemaConfig.Status - _spec.OnConflict = sc.conflict - if value, ok := sc.mutation.Version(); ok { - _spec.SetField(status.FieldVersion, field.TypeInt64, value) - _node.Version = value - } - if value, ok := sc.mutation.UpdatedAt(); ok { - _spec.SetField(status.FieldUpdatedAt, field.TypeTime, value) - _node.UpdatedAt = value - } - if value, ok := sc.mutation.Status(); ok { - _spec.SetField(status.FieldStatus, field.TypeEnum, value) - _node.Status = value - } - return _node, _spec -} - -// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause -// of the `INSERT` statement. For example: -// -// client.Status.Create(). -// SetVersion(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.StatusUpsert) { -// SetVersion(v+v). -// }). -// Exec(ctx) -func (sc *StatusCreate) OnConflict(opts ...sql.ConflictOption) *StatusUpsertOne { - sc.conflict = opts - return &StatusUpsertOne{ - create: sc, - } -} - -// OnConflictColumns calls `OnConflict` and configures the columns -// as conflict target. Using this option is equivalent to using: -// -// client.Status.Create(). -// OnConflict(sql.ConflictColumns(columns...)). -// Exec(ctx) -func (sc *StatusCreate) OnConflictColumns(columns ...string) *StatusUpsertOne { - sc.conflict = append(sc.conflict, sql.ConflictColumns(columns...)) - return &StatusUpsertOne{ - create: sc, - } -} - -type ( - // StatusUpsertOne is the builder for "upsert"-ing - // one Status node. - StatusUpsertOne struct { - create *StatusCreate - } - - // StatusUpsert is the "OnConflict" setter. - StatusUpsert struct { - *sql.UpdateSet - } -) - -// SetVersion sets the "version" field. -func (u *StatusUpsert) SetVersion(v int64) *StatusUpsert { - u.Set(status.FieldVersion, v) - return u -} - -// UpdateVersion sets the "version" field to the value that was provided on create. -func (u *StatusUpsert) UpdateVersion() *StatusUpsert { - u.SetExcluded(status.FieldVersion) - return u -} - -// AddVersion adds v to the "version" field. -func (u *StatusUpsert) AddVersion(v int64) *StatusUpsert { - u.Add(status.FieldVersion, v) - return u -} - -// SetUpdatedAt sets the "updated_at" field. -func (u *StatusUpsert) SetUpdatedAt(v time.Time) *StatusUpsert { - u.Set(status.FieldUpdatedAt, v) - return u -} - -// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. -func (u *StatusUpsert) UpdateUpdatedAt() *StatusUpsert { - u.SetExcluded(status.FieldUpdatedAt) - return u -} - -// SetStatus sets the "status" field. -func (u *StatusUpsert) SetStatus(v status.Status) *StatusUpsert { - u.Set(status.FieldStatus, v) - return u -} - -// UpdateStatus sets the "status" field to the value that was provided on create. -func (u *StatusUpsert) UpdateStatus() *StatusUpsert { - u.SetExcluded(status.FieldStatus) - return u -} - -// UpdateNewValues updates the mutable fields using the new values that were set on create. -// Using this option is equivalent to using: -// -// client.Status.Create(). -// OnConflict( -// sql.ResolveWithNewValues(), -// ). -// Exec(ctx) -func (u *StatusUpsertOne) UpdateNewValues() *StatusUpsertOne { - u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) - return u -} - -// Ignore sets each column to itself in case of conflict. -// Using this option is equivalent to using: -// -// client.Status.Create(). -// OnConflict(sql.ResolveWithIgnore()). -// Exec(ctx) -func (u *StatusUpsertOne) Ignore() *StatusUpsertOne { - 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 *StatusUpsertOne) DoNothing() *StatusUpsertOne { - u.create.conflict = append(u.create.conflict, sql.DoNothing()) - return u -} - -// Update allows overriding fields `UPDATE` values. See the StatusCreate.OnConflict -// documentation for more info. -func (u *StatusUpsertOne) Update(set func(*StatusUpsert)) *StatusUpsertOne { - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { - set(&StatusUpsert{UpdateSet: update}) - })) - return u -} - -// SetVersion sets the "version" field. -func (u *StatusUpsertOne) SetVersion(v int64) *StatusUpsertOne { - return u.Update(func(s *StatusUpsert) { - s.SetVersion(v) - }) -} - -// AddVersion adds v to the "version" field. -func (u *StatusUpsertOne) AddVersion(v int64) *StatusUpsertOne { - return u.Update(func(s *StatusUpsert) { - s.AddVersion(v) - }) -} - -// UpdateVersion sets the "version" field to the value that was provided on create. -func (u *StatusUpsertOne) UpdateVersion() *StatusUpsertOne { - return u.Update(func(s *StatusUpsert) { - s.UpdateVersion() - }) -} - -// SetUpdatedAt sets the "updated_at" field. -func (u *StatusUpsertOne) SetUpdatedAt(v time.Time) *StatusUpsertOne { - return u.Update(func(s *StatusUpsert) { - s.SetUpdatedAt(v) - }) -} - -// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. -func (u *StatusUpsertOne) UpdateUpdatedAt() *StatusUpsertOne { - return u.Update(func(s *StatusUpsert) { - s.UpdateUpdatedAt() - }) -} - -// SetStatus sets the "status" field. -func (u *StatusUpsertOne) SetStatus(v status.Status) *StatusUpsertOne { - return u.Update(func(s *StatusUpsert) { - s.SetStatus(v) - }) -} - -// UpdateStatus sets the "status" field to the value that was provided on create. -func (u *StatusUpsertOne) UpdateStatus() *StatusUpsertOne { - return u.Update(func(s *StatusUpsert) { - s.UpdateStatus() - }) -} - -// Exec executes the query. -func (u *StatusUpsertOne) Exec(ctx context.Context) error { - if len(u.create.conflict) == 0 { - return errors.New("models: missing options for StatusCreate.OnConflict") - } - return u.create.Exec(ctx) -} - -// ExecX is like Exec, but panics if an error occurs. -func (u *StatusUpsertOne) 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 *StatusUpsertOne) ID(ctx context.Context) (id int, 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 *StatusUpsertOne) IDX(ctx context.Context) int { - id, err := u.ID(ctx) - if err != nil { - panic(err) - } - return id -} - -// StatusCreateBulk is the builder for creating many Status entities in bulk. -type StatusCreateBulk struct { - config - err error - builders []*StatusCreate - conflict []sql.ConflictOption -} - -// Save creates the Status entities in the database. -func (scb *StatusCreateBulk) Save(ctx context.Context) ([]*Status, error) { - if scb.err != nil { - return nil, scb.err - } - specs := make([]*sqlgraph.CreateSpec, len(scb.builders)) - nodes := make([]*Status, len(scb.builders)) - mutators := make([]Mutator, len(scb.builders)) - for i := range scb.builders { - func(i int, root context.Context) { - builder := scb.builders[i] - builder.defaults() - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*StatusMutation) - 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, scb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - spec.OnConflict = scb.conflict - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, scb.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 = int(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, scb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (scb *StatusCreateBulk) SaveX(ctx context.Context) []*Status { - v, err := scb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (scb *StatusCreateBulk) Exec(ctx context.Context) error { - _, err := scb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (scb *StatusCreateBulk) ExecX(ctx context.Context) { - if err := scb.Exec(ctx); err != nil { - panic(err) - } -} - -// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause -// of the `INSERT` statement. For example: -// -// client.Status.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.StatusUpsert) { -// SetVersion(v+v). -// }). -// Exec(ctx) -func (scb *StatusCreateBulk) OnConflict(opts ...sql.ConflictOption) *StatusUpsertBulk { - scb.conflict = opts - return &StatusUpsertBulk{ - create: scb, - } -} - -// OnConflictColumns calls `OnConflict` and configures the columns -// as conflict target. Using this option is equivalent to using: -// -// client.Status.Create(). -// OnConflict(sql.ConflictColumns(columns...)). -// Exec(ctx) -func (scb *StatusCreateBulk) OnConflictColumns(columns ...string) *StatusUpsertBulk { - scb.conflict = append(scb.conflict, sql.ConflictColumns(columns...)) - return &StatusUpsertBulk{ - create: scb, - } -} - -// StatusUpsertBulk is the builder for "upsert"-ing -// a bulk of Status nodes. -type StatusUpsertBulk struct { - create *StatusCreateBulk -} - -// UpdateNewValues updates the mutable fields using the new values that -// were set on create. Using this option is equivalent to using: -// -// client.Status.Create(). -// OnConflict( -// sql.ResolveWithNewValues(), -// ). -// Exec(ctx) -func (u *StatusUpsertBulk) UpdateNewValues() *StatusUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) - return u -} - -// Ignore sets each column to itself in case of conflict. -// Using this option is equivalent to using: -// -// client.Status.Create(). -// OnConflict(sql.ResolveWithIgnore()). -// Exec(ctx) -func (u *StatusUpsertBulk) Ignore() *StatusUpsertBulk { - 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 *StatusUpsertBulk) DoNothing() *StatusUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.DoNothing()) - return u -} - -// Update allows overriding fields `UPDATE` values. See the StatusCreateBulk.OnConflict -// documentation for more info. -func (u *StatusUpsertBulk) Update(set func(*StatusUpsert)) *StatusUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { - set(&StatusUpsert{UpdateSet: update}) - })) - return u -} - -// SetVersion sets the "version" field. -func (u *StatusUpsertBulk) SetVersion(v int64) *StatusUpsertBulk { - return u.Update(func(s *StatusUpsert) { - s.SetVersion(v) - }) -} - -// AddVersion adds v to the "version" field. -func (u *StatusUpsertBulk) AddVersion(v int64) *StatusUpsertBulk { - return u.Update(func(s *StatusUpsert) { - s.AddVersion(v) - }) -} - -// UpdateVersion sets the "version" field to the value that was provided on create. -func (u *StatusUpsertBulk) UpdateVersion() *StatusUpsertBulk { - return u.Update(func(s *StatusUpsert) { - s.UpdateVersion() - }) -} - -// SetUpdatedAt sets the "updated_at" field. -func (u *StatusUpsertBulk) SetUpdatedAt(v time.Time) *StatusUpsertBulk { - return u.Update(func(s *StatusUpsert) { - s.SetUpdatedAt(v) - }) -} - -// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. -func (u *StatusUpsertBulk) UpdateUpdatedAt() *StatusUpsertBulk { - return u.Update(func(s *StatusUpsert) { - s.UpdateUpdatedAt() - }) -} - -// SetStatus sets the "status" field. -func (u *StatusUpsertBulk) SetStatus(v status.Status) *StatusUpsertBulk { - return u.Update(func(s *StatusUpsert) { - s.SetStatus(v) - }) -} - -// UpdateStatus sets the "status" field to the value that was provided on create. -func (u *StatusUpsertBulk) UpdateStatus() *StatusUpsertBulk { - return u.Update(func(s *StatusUpsert) { - s.UpdateStatus() - }) -} - -// Exec executes the query. -func (u *StatusUpsertBulk) Exec(ctx context.Context) error { - if u.create.err != nil { - return u.create.err - } - for i, b := range u.create.builders { - if len(b.conflict) != 0 { - return fmt.Errorf("models: OnConflict was set for builder %d. Set it on the StatusCreateBulk instead", i) - } - } - if len(u.create.conflict) == 0 { - return errors.New("models: missing options for StatusCreateBulk.OnConflict") - } - return u.create.Exec(ctx) -} - -// ExecX is like Exec, but panics if an error occurs. -func (u *StatusUpsertBulk) ExecX(ctx context.Context) { - if err := u.create.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/packages/orchestrator/internal/pkg/models/status_delete.go b/packages/orchestrator/internal/pkg/models/status_delete.go deleted file mode 100644 index cfea8babb..000000000 --- a/packages/orchestrator/internal/pkg/models/status_delete.go +++ /dev/null @@ -1,91 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" -) - -// StatusDelete is the builder for deleting a Status entity. -type StatusDelete struct { - config - hooks []Hook - mutation *StatusMutation -} - -// Where appends a list predicates to the StatusDelete builder. -func (sd *StatusDelete) Where(ps ...predicate.Status) *StatusDelete { - sd.mutation.Where(ps...) - return sd -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (sd *StatusDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, sd.sqlExec, sd.mutation, sd.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (sd *StatusDelete) ExecX(ctx context.Context) int { - n, err := sd.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (sd *StatusDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(status.Table, sqlgraph.NewFieldSpec(status.FieldID, field.TypeInt)) - _spec.Node.Schema = sd.schemaConfig.Status - ctx = internal.NewSchemaConfigContext(ctx, sd.schemaConfig) - if ps := sd.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, sd.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - sd.mutation.done = true - return affected, err -} - -// StatusDeleteOne is the builder for deleting a single Status entity. -type StatusDeleteOne struct { - sd *StatusDelete -} - -// Where appends a list predicates to the StatusDelete builder. -func (sdo *StatusDeleteOne) Where(ps ...predicate.Status) *StatusDeleteOne { - sdo.sd.mutation.Where(ps...) - return sdo -} - -// Exec executes the deletion query. -func (sdo *StatusDeleteOne) Exec(ctx context.Context) error { - n, err := sdo.sd.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{status.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (sdo *StatusDeleteOne) ExecX(ctx context.Context) { - if err := sdo.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/packages/orchestrator/internal/pkg/models/status_query.go b/packages/orchestrator/internal/pkg/models/status_query.go deleted file mode 100644 index d4c0b59c0..000000000 --- a/packages/orchestrator/internal/pkg/models/status_query.go +++ /dev/null @@ -1,556 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" -) - -// StatusQuery is the builder for querying Status entities. -type StatusQuery struct { - config - ctx *QueryContext - order []status.OrderOption - inters []Interceptor - predicates []predicate.Status - 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 StatusQuery builder. -func (sq *StatusQuery) Where(ps ...predicate.Status) *StatusQuery { - sq.predicates = append(sq.predicates, ps...) - return sq -} - -// Limit the number of records to be returned by this query. -func (sq *StatusQuery) Limit(limit int) *StatusQuery { - sq.ctx.Limit = &limit - return sq -} - -// Offset to start from. -func (sq *StatusQuery) Offset(offset int) *StatusQuery { - sq.ctx.Offset = &offset - return sq -} - -// 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 (sq *StatusQuery) Unique(unique bool) *StatusQuery { - sq.ctx.Unique = &unique - return sq -} - -// Order specifies how the records should be ordered. -func (sq *StatusQuery) Order(o ...status.OrderOption) *StatusQuery { - sq.order = append(sq.order, o...) - return sq -} - -// First returns the first Status entity from the query. -// Returns a *NotFoundError when no Status was found. -func (sq *StatusQuery) First(ctx context.Context) (*Status, error) { - nodes, err := sq.Limit(1).All(setContextOp(ctx, sq.ctx, "First")) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{status.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (sq *StatusQuery) FirstX(ctx context.Context) *Status { - node, err := sq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first Status ID from the query. -// Returns a *NotFoundError when no Status ID was found. -func (sq *StatusQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = sq.Limit(1).IDs(setContextOp(ctx, sq.ctx, "FirstID")); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{status.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (sq *StatusQuery) FirstIDX(ctx context.Context) int { - id, err := sq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single Status entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one Status entity is found. -// Returns a *NotFoundError when no Status entities are found. -func (sq *StatusQuery) Only(ctx context.Context) (*Status, error) { - nodes, err := sq.Limit(2).All(setContextOp(ctx, sq.ctx, "Only")) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{status.Label} - default: - return nil, &NotSingularError{status.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (sq *StatusQuery) OnlyX(ctx context.Context) *Status { - node, err := sq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only Status ID in the query. -// Returns a *NotSingularError when more than one Status ID is found. -// Returns a *NotFoundError when no entities are found. -func (sq *StatusQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = sq.Limit(2).IDs(setContextOp(ctx, sq.ctx, "OnlyID")); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{status.Label} - default: - err = &NotSingularError{status.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (sq *StatusQuery) OnlyIDX(ctx context.Context) int { - id, err := sq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of StatusSlice. -func (sq *StatusQuery) All(ctx context.Context) ([]*Status, error) { - ctx = setContextOp(ctx, sq.ctx, "All") - if err := sq.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*Status, *StatusQuery]() - return withInterceptors[[]*Status](ctx, sq, qr, sq.inters) -} - -// AllX is like All, but panics if an error occurs. -func (sq *StatusQuery) AllX(ctx context.Context) []*Status { - nodes, err := sq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of Status IDs. -func (sq *StatusQuery) IDs(ctx context.Context) (ids []int, err error) { - if sq.ctx.Unique == nil && sq.path != nil { - sq.Unique(true) - } - ctx = setContextOp(ctx, sq.ctx, "IDs") - if err = sq.Select(status.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (sq *StatusQuery) IDsX(ctx context.Context) []int { - ids, err := sq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (sq *StatusQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, sq.ctx, "Count") - if err := sq.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, sq, querierCount[*StatusQuery](), sq.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (sq *StatusQuery) CountX(ctx context.Context) int { - count, err := sq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (sq *StatusQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, sq.ctx, "Exist") - switch _, err := sq.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("models: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (sq *StatusQuery) ExistX(ctx context.Context) bool { - exist, err := sq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the StatusQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (sq *StatusQuery) Clone() *StatusQuery { - if sq == nil { - return nil - } - return &StatusQuery{ - config: sq.config, - ctx: sq.ctx.Clone(), - order: append([]status.OrderOption{}, sq.order...), - inters: append([]Interceptor{}, sq.inters...), - predicates: append([]predicate.Status{}, sq.predicates...), - // clone intermediate query. - sql: sq.sql.Clone(), - path: sq.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 { -// Version int64 `json:"version,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.Status.Query(). -// GroupBy(status.FieldVersion). -// Aggregate(models.Count()). -// Scan(ctx, &v) -func (sq *StatusQuery) GroupBy(field string, fields ...string) *StatusGroupBy { - sq.ctx.Fields = append([]string{field}, fields...) - grbuild := &StatusGroupBy{build: sq} - grbuild.flds = &sq.ctx.Fields - grbuild.label = status.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 { -// Version int64 `json:"version,omitempty"` -// } -// -// client.Status.Query(). -// Select(status.FieldVersion). -// Scan(ctx, &v) -func (sq *StatusQuery) Select(fields ...string) *StatusSelect { - sq.ctx.Fields = append(sq.ctx.Fields, fields...) - sbuild := &StatusSelect{StatusQuery: sq} - sbuild.label = status.Label - sbuild.flds, sbuild.scan = &sq.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a StatusSelect configured with the given aggregations. -func (sq *StatusQuery) Aggregate(fns ...AggregateFunc) *StatusSelect { - return sq.Select().Aggregate(fns...) -} - -func (sq *StatusQuery) prepareQuery(ctx context.Context) error { - for _, inter := range sq.inters { - if inter == nil { - return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, sq); err != nil { - return err - } - } - } - for _, f := range sq.ctx.Fields { - if !status.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} - } - } - if sq.path != nil { - prev, err := sq.path(ctx) - if err != nil { - return err - } - sq.sql = prev - } - return nil -} - -func (sq *StatusQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Status, error) { - var ( - nodes = []*Status{} - _spec = sq.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*Status).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &Status{config: sq.config} - nodes = append(nodes, node) - return node.assignValues(columns, values) - } - _spec.Node.Schema = sq.schemaConfig.Status - ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) - if len(sq.modifiers) > 0 { - _spec.Modifiers = sq.modifiers - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, sq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (sq *StatusQuery) sqlCount(ctx context.Context) (int, error) { - _spec := sq.querySpec() - _spec.Node.Schema = sq.schemaConfig.Status - ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) - if len(sq.modifiers) > 0 { - _spec.Modifiers = sq.modifiers - } - _spec.Node.Columns = sq.ctx.Fields - if len(sq.ctx.Fields) > 0 { - _spec.Unique = sq.ctx.Unique != nil && *sq.ctx.Unique - } - return sqlgraph.CountNodes(ctx, sq.driver, _spec) -} - -func (sq *StatusQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(status.Table, status.Columns, sqlgraph.NewFieldSpec(status.FieldID, field.TypeInt)) - _spec.From = sq.sql - if unique := sq.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if sq.path != nil { - _spec.Unique = true - } - if fields := sq.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, status.FieldID) - for i := range fields { - if fields[i] != status.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := sq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := sq.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := sq.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := sq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (sq *StatusQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(sq.driver.Dialect()) - t1 := builder.Table(status.Table) - columns := sq.ctx.Fields - if len(columns) == 0 { - columns = status.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if sq.sql != nil { - selector = sq.sql - selector.Select(selector.Columns(columns...)...) - } - if sq.ctx.Unique != nil && *sq.ctx.Unique { - selector.Distinct() - } - t1.Schema(sq.schemaConfig.Status) - ctx = internal.NewSchemaConfigContext(ctx, sq.schemaConfig) - selector.WithContext(ctx) - for _, m := range sq.modifiers { - m(selector) - } - for _, p := range sq.predicates { - p(selector) - } - for _, p := range sq.order { - p(selector) - } - if offset := sq.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 := sq.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// Modify adds a query modifier for attaching custom logic to queries. -func (sq *StatusQuery) Modify(modifiers ...func(s *sql.Selector)) *StatusSelect { - sq.modifiers = append(sq.modifiers, modifiers...) - return sq.Select() -} - -// StatusGroupBy is the group-by builder for Status entities. -type StatusGroupBy struct { - selector - build *StatusQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (sgb *StatusGroupBy) Aggregate(fns ...AggregateFunc) *StatusGroupBy { - sgb.fns = append(sgb.fns, fns...) - return sgb -} - -// Scan applies the selector query and scans the result into the given value. -func (sgb *StatusGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, sgb.build.ctx, "GroupBy") - if err := sgb.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*StatusQuery, *StatusGroupBy](ctx, sgb.build, sgb, sgb.build.inters, v) -} - -func (sgb *StatusGroupBy) sqlScan(ctx context.Context, root *StatusQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(sgb.fns)) - for _, fn := range sgb.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*sgb.flds)+len(sgb.fns)) - for _, f := range *sgb.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*sgb.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := sgb.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// StatusSelect is the builder for selecting fields of Status entities. -type StatusSelect struct { - *StatusQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (ss *StatusSelect) Aggregate(fns ...AggregateFunc) *StatusSelect { - ss.fns = append(ss.fns, fns...) - return ss -} - -// Scan applies the selector query and scans the result into the given value. -func (ss *StatusSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, ss.ctx, "Select") - if err := ss.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*StatusQuery, *StatusSelect](ctx, ss.StatusQuery, ss, ss.inters, v) -} - -func (ss *StatusSelect) sqlScan(ctx context.Context, root *StatusQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(ss.fns)) - for _, fn := range ss.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*ss.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 := ss.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// Modify adds a query modifier for attaching custom logic to queries. -func (ss *StatusSelect) Modify(modifiers ...func(s *sql.Selector)) *StatusSelect { - ss.modifiers = append(ss.modifiers, modifiers...) - return ss -} diff --git a/packages/orchestrator/internal/pkg/models/status_update.go b/packages/orchestrator/internal/pkg/models/status_update.go deleted file mode 100644 index a53bf6cf5..000000000 --- a/packages/orchestrator/internal/pkg/models/status_update.go +++ /dev/null @@ -1,355 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/internal" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/predicate" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/status" -) - -// StatusUpdate is the builder for updating Status entities. -type StatusUpdate struct { - config - hooks []Hook - mutation *StatusMutation - modifiers []func(*sql.UpdateBuilder) -} - -// Where appends a list predicates to the StatusUpdate builder. -func (su *StatusUpdate) Where(ps ...predicate.Status) *StatusUpdate { - su.mutation.Where(ps...) - return su -} - -// SetVersion sets the "version" field. -func (su *StatusUpdate) SetVersion(i int64) *StatusUpdate { - su.mutation.ResetVersion() - su.mutation.SetVersion(i) - return su -} - -// SetNillableVersion sets the "version" field if the given value is not nil. -func (su *StatusUpdate) SetNillableVersion(i *int64) *StatusUpdate { - if i != nil { - su.SetVersion(*i) - } - return su -} - -// AddVersion adds i to the "version" field. -func (su *StatusUpdate) AddVersion(i int64) *StatusUpdate { - su.mutation.AddVersion(i) - return su -} - -// SetUpdatedAt sets the "updated_at" field. -func (su *StatusUpdate) SetUpdatedAt(t time.Time) *StatusUpdate { - su.mutation.SetUpdatedAt(t) - return su -} - -// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. -func (su *StatusUpdate) SetNillableUpdatedAt(t *time.Time) *StatusUpdate { - if t != nil { - su.SetUpdatedAt(*t) - } - return su -} - -// SetStatus sets the "status" field. -func (su *StatusUpdate) SetStatus(s status.Status) *StatusUpdate { - su.mutation.SetStatus(s) - return su -} - -// SetNillableStatus sets the "status" field if the given value is not nil. -func (su *StatusUpdate) SetNillableStatus(s *status.Status) *StatusUpdate { - if s != nil { - su.SetStatus(*s) - } - return su -} - -// Mutation returns the StatusMutation object of the builder. -func (su *StatusUpdate) Mutation() *StatusMutation { - return su.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (su *StatusUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, su.sqlSave, su.mutation, su.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (su *StatusUpdate) SaveX(ctx context.Context) int { - affected, err := su.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (su *StatusUpdate) Exec(ctx context.Context) error { - _, err := su.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (su *StatusUpdate) ExecX(ctx context.Context) { - if err := su.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (su *StatusUpdate) check() error { - if v, ok := su.mutation.Version(); ok { - if err := status.VersionValidator(v); err != nil { - return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Status.version": %w`, err)} - } - } - if v, ok := su.mutation.Status(); ok { - if err := status.StatusValidator(v); err != nil { - return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Status.status": %w`, err)} - } - } - return nil -} - -// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. -func (su *StatusUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *StatusUpdate { - su.modifiers = append(su.modifiers, modifiers...) - return su -} - -func (su *StatusUpdate) sqlSave(ctx context.Context) (n int, err error) { - if err := su.check(); err != nil { - return n, err - } - _spec := sqlgraph.NewUpdateSpec(status.Table, status.Columns, sqlgraph.NewFieldSpec(status.FieldID, field.TypeInt)) - if ps := su.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := su.mutation.Version(); ok { - _spec.SetField(status.FieldVersion, field.TypeInt64, value) - } - if value, ok := su.mutation.AddedVersion(); ok { - _spec.AddField(status.FieldVersion, field.TypeInt64, value) - } - if value, ok := su.mutation.UpdatedAt(); ok { - _spec.SetField(status.FieldUpdatedAt, field.TypeTime, value) - } - if value, ok := su.mutation.Status(); ok { - _spec.SetField(status.FieldStatus, field.TypeEnum, value) - } - _spec.Node.Schema = su.schemaConfig.Status - ctx = internal.NewSchemaConfigContext(ctx, su.schemaConfig) - _spec.AddModifiers(su.modifiers...) - if n, err = sqlgraph.UpdateNodes(ctx, su.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{status.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - su.mutation.done = true - return n, nil -} - -// StatusUpdateOne is the builder for updating a single Status entity. -type StatusUpdateOne struct { - config - fields []string - hooks []Hook - mutation *StatusMutation - modifiers []func(*sql.UpdateBuilder) -} - -// SetVersion sets the "version" field. -func (suo *StatusUpdateOne) SetVersion(i int64) *StatusUpdateOne { - suo.mutation.ResetVersion() - suo.mutation.SetVersion(i) - return suo -} - -// SetNillableVersion sets the "version" field if the given value is not nil. -func (suo *StatusUpdateOne) SetNillableVersion(i *int64) *StatusUpdateOne { - if i != nil { - suo.SetVersion(*i) - } - return suo -} - -// AddVersion adds i to the "version" field. -func (suo *StatusUpdateOne) AddVersion(i int64) *StatusUpdateOne { - suo.mutation.AddVersion(i) - return suo -} - -// SetUpdatedAt sets the "updated_at" field. -func (suo *StatusUpdateOne) SetUpdatedAt(t time.Time) *StatusUpdateOne { - suo.mutation.SetUpdatedAt(t) - return suo -} - -// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. -func (suo *StatusUpdateOne) SetNillableUpdatedAt(t *time.Time) *StatusUpdateOne { - if t != nil { - suo.SetUpdatedAt(*t) - } - return suo -} - -// SetStatus sets the "status" field. -func (suo *StatusUpdateOne) SetStatus(s status.Status) *StatusUpdateOne { - suo.mutation.SetStatus(s) - return suo -} - -// SetNillableStatus sets the "status" field if the given value is not nil. -func (suo *StatusUpdateOne) SetNillableStatus(s *status.Status) *StatusUpdateOne { - if s != nil { - suo.SetStatus(*s) - } - return suo -} - -// Mutation returns the StatusMutation object of the builder. -func (suo *StatusUpdateOne) Mutation() *StatusMutation { - return suo.mutation -} - -// Where appends a list predicates to the StatusUpdate builder. -func (suo *StatusUpdateOne) Where(ps ...predicate.Status) *StatusUpdateOne { - suo.mutation.Where(ps...) - return suo -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (suo *StatusUpdateOne) Select(field string, fields ...string) *StatusUpdateOne { - suo.fields = append([]string{field}, fields...) - return suo -} - -// Save executes the query and returns the updated Status entity. -func (suo *StatusUpdateOne) Save(ctx context.Context) (*Status, error) { - return withHooks(ctx, suo.sqlSave, suo.mutation, suo.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (suo *StatusUpdateOne) SaveX(ctx context.Context) *Status { - node, err := suo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (suo *StatusUpdateOne) Exec(ctx context.Context) error { - _, err := suo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (suo *StatusUpdateOne) ExecX(ctx context.Context) { - if err := suo.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (suo *StatusUpdateOne) check() error { - if v, ok := suo.mutation.Version(); ok { - if err := status.VersionValidator(v); err != nil { - return &ValidationError{Name: "version", err: fmt.Errorf(`models: validator failed for field "Status.version": %w`, err)} - } - } - if v, ok := suo.mutation.Status(); ok { - if err := status.StatusValidator(v); err != nil { - return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Status.status": %w`, err)} - } - } - return nil -} - -// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. -func (suo *StatusUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *StatusUpdateOne { - suo.modifiers = append(suo.modifiers, modifiers...) - return suo -} - -func (suo *StatusUpdateOne) sqlSave(ctx context.Context) (_node *Status, err error) { - if err := suo.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(status.Table, status.Columns, sqlgraph.NewFieldSpec(status.FieldID, field.TypeInt)) - id, ok := suo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Status.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := suo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, status.FieldID) - for _, f := range fields { - if !status.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} - } - if f != status.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := suo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := suo.mutation.Version(); ok { - _spec.SetField(status.FieldVersion, field.TypeInt64, value) - } - if value, ok := suo.mutation.AddedVersion(); ok { - _spec.AddField(status.FieldVersion, field.TypeInt64, value) - } - if value, ok := suo.mutation.UpdatedAt(); ok { - _spec.SetField(status.FieldUpdatedAt, field.TypeTime, value) - } - if value, ok := suo.mutation.Status(); ok { - _spec.SetField(status.FieldStatus, field.TypeEnum, value) - } - _spec.Node.Schema = suo.schemaConfig.Status - ctx = internal.NewSchemaConfigContext(ctx, suo.schemaConfig) - _spec.AddModifiers(suo.modifiers...) - _node = &Status{config: suo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, suo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{status.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - suo.mutation.done = true - return _node, nil -} diff --git a/packages/orchestrator/internal/pkg/models/tx.go b/packages/orchestrator/internal/pkg/models/tx.go deleted file mode 100644 index 8e1937981..000000000 --- a/packages/orchestrator/internal/pkg/models/tx.go +++ /dev/null @@ -1,213 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package models - -import ( - "context" - "sync" - - "entgo.io/ent/dialect" -) - -// Tx is a transactional client that is created by calling Client.Tx(). -type Tx struct { - config - // Sandbox is the client for interacting with the Sandbox builders. - Sandbox *SandboxClient - // Status is the client for interacting with the Status builders. - Status *StatusClient - - // lazily loaded. - client *Client - clientOnce sync.Once - // ctx lives for the life of the transaction. It is - // the same context used by the underlying connection. - ctx context.Context -} - -type ( - // Committer is the interface that wraps the Commit method. - Committer interface { - Commit(context.Context, *Tx) error - } - - // The CommitFunc type is an adapter to allow the use of ordinary - // function as a Committer. If f is a function with the appropriate - // signature, CommitFunc(f) is a Committer that calls f. - CommitFunc func(context.Context, *Tx) error - - // CommitHook defines the "commit middleware". A function that gets a Committer - // and returns a Committer. For example: - // - // hook := func(next ent.Committer) ent.Committer { - // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { - // // Do some stuff before. - // if err := next.Commit(ctx, tx); err != nil { - // return err - // } - // // Do some stuff after. - // return nil - // }) - // } - // - CommitHook func(Committer) Committer -) - -// Commit calls f(ctx, m). -func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { - return f(ctx, tx) -} - -// Commit commits the transaction. -func (tx *Tx) Commit() error { - txDriver := tx.config.driver.(*txDriver) - var fn Committer = CommitFunc(func(context.Context, *Tx) error { - return txDriver.tx.Commit() - }) - txDriver.mu.Lock() - hooks := append([]CommitHook(nil), txDriver.onCommit...) - txDriver.mu.Unlock() - for i := len(hooks) - 1; i >= 0; i-- { - fn = hooks[i](fn) - } - return fn.Commit(tx.ctx, tx) -} - -// OnCommit adds a hook to call on commit. -func (tx *Tx) OnCommit(f CommitHook) { - txDriver := tx.config.driver.(*txDriver) - txDriver.mu.Lock() - txDriver.onCommit = append(txDriver.onCommit, f) - txDriver.mu.Unlock() -} - -type ( - // Rollbacker is the interface that wraps the Rollback method. - Rollbacker interface { - Rollback(context.Context, *Tx) error - } - - // The RollbackFunc type is an adapter to allow the use of ordinary - // function as a Rollbacker. If f is a function with the appropriate - // signature, RollbackFunc(f) is a Rollbacker that calls f. - RollbackFunc func(context.Context, *Tx) error - - // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker - // and returns a Rollbacker. For example: - // - // hook := func(next ent.Rollbacker) ent.Rollbacker { - // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { - // // Do some stuff before. - // if err := next.Rollback(ctx, tx); err != nil { - // return err - // } - // // Do some stuff after. - // return nil - // }) - // } - // - RollbackHook func(Rollbacker) Rollbacker -) - -// Rollback calls f(ctx, m). -func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { - return f(ctx, tx) -} - -// Rollback rollbacks the transaction. -func (tx *Tx) Rollback() error { - txDriver := tx.config.driver.(*txDriver) - var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { - return txDriver.tx.Rollback() - }) - txDriver.mu.Lock() - hooks := append([]RollbackHook(nil), txDriver.onRollback...) - txDriver.mu.Unlock() - for i := len(hooks) - 1; i >= 0; i-- { - fn = hooks[i](fn) - } - return fn.Rollback(tx.ctx, tx) -} - -// OnRollback adds a hook to call on rollback. -func (tx *Tx) OnRollback(f RollbackHook) { - txDriver := tx.config.driver.(*txDriver) - txDriver.mu.Lock() - txDriver.onRollback = append(txDriver.onRollback, f) - txDriver.mu.Unlock() -} - -// Client returns a Client that binds to current transaction. -func (tx *Tx) Client() *Client { - tx.clientOnce.Do(func() { - tx.client = &Client{config: tx.config} - tx.client.init() - }) - return tx.client -} - -func (tx *Tx) init() { - tx.Sandbox = NewSandboxClient(tx.config) - tx.Status = NewStatusClient(tx.config) -} - -// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. -// The idea is to support transactions without adding any extra code to the builders. -// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. -// Commit and Rollback are nop for the internal builders and the user must call one -// of them in order to commit or rollback the transaction. -// -// If a closed transaction is embedded in one of the generated entities, and the entity -// applies a query, for example: Sandbox.QueryXXX(), the query will be executed -// through the driver which created this transaction. -// -// Note that txDriver is not goroutine safe. -type txDriver struct { - // the driver we started the transaction from. - drv dialect.Driver - // tx is the underlying transaction. - tx dialect.Tx - // completion hooks. - mu sync.Mutex - onCommit []CommitHook - onRollback []RollbackHook -} - -// newTx creates a new transactional driver. -func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { - tx, err := drv.Tx(ctx) - if err != nil { - return nil, err - } - return &txDriver{tx: tx, drv: drv}, nil -} - -// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls -// from the internal builders. Should be called only by the internal builders. -func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } - -// Dialect returns the dialect of the driver we started the transaction from. -func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } - -// Close is a nop close. -func (*txDriver) Close() error { return nil } - -// Commit is a nop commit for the internal builders. -// User must call `Tx.Commit` in order to commit the transaction. -func (*txDriver) Commit() error { return nil } - -// Rollback is a nop rollback for the internal builders. -// User must call `Tx.Rollback` in order to rollback the transaction. -func (*txDriver) Rollback() error { return nil } - -// Exec calls tx.Exec. -func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { - return tx.tx.Exec(ctx, query, args, v) -} - -// Query calls tx.Query. -func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { - return tx.tx.Query(ctx, query, args, v) -} - -var _ dialect.Driver = (*txDriver)(nil) diff --git a/packages/orchestrator/internal/pkg/schema/sandbox.go b/packages/orchestrator/internal/pkg/schema/sandbox.go deleted file mode 100644 index 6d4721447..000000000 --- a/packages/orchestrator/internal/pkg/schema/sandbox.go +++ /dev/null @@ -1,32 +0,0 @@ -package schema - -import ( - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect/entsql" - "entgo.io/ent/schema/field" -) - -type Sandbox struct { - ent.Schema -} - -func (Sandbox) Fields() []ent.Field { - return []ent.Field{ - field.String("id").Unique().Immutable().NotEmpty(), - field.Time("started_at").Immutable().Default(time.Now). - Annotations( - entsql.Default("CURRENT_TIMESTAMP"), - ), - field.Time("updated_at").Default(time.Now), - field.Time("terminated_at").Nillable(), - field.Time("deadline").Nillable(), - field.Enum("status").Values("pending", "running", "paused", "terminated").Default("pending"), - field.Int64("duration_ms").NonNegative(), - field.Int64("version").NonNegative().Comment("an incrementing clock of this "), - field.Int64("global_version").NonNegative().Comment("a record of the version of the global state of the last modification."), - // TODO: should we store more data persistently about sandboxes? - // TODO: mechanism to cleanup - } -} diff --git a/packages/orchestrator/internal/pkg/schema/status.go b/packages/orchestrator/internal/pkg/schema/status.go deleted file mode 100644 index ca28ec432..000000000 --- a/packages/orchestrator/internal/pkg/schema/status.go +++ /dev/null @@ -1,22 +0,0 @@ -package schema - -import ( - "time" - - "entgo.io/ent" - "entgo.io/ent/schema/field" -) - -// The Status table stores the global status of the -// orchestrator. Exists to have a global version/clock -type Status struct { - ent.Schema -} - -func (Status) Fields() []ent.Field { - return []ent.Field{ - field.Int64("version").NonNegative().Unique(), - field.Time("updated_at").Default(time.Now), - field.Enum("status").Values("initializing", "running", "draining", "terminating").Default("running"), - } -} diff --git a/packages/orchestrator/internal/server/main.go b/packages/orchestrator/internal/server/main.go index af9bc0f5d..0c9f44f64 100644 --- a/packages/orchestrator/internal/server/main.go +++ b/packages/orchestrator/internal/server/main.go @@ -24,13 +24,13 @@ import ( "entgo.io/ent/dialect/sql" "github.com/e2b-dev/infra/packages/orchestrator/internal/db" "github.com/e2b-dev/infra/packages/orchestrator/internal/dns" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/network" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/template" e2bgrpc "github.com/e2b-dev/infra/packages/shared/pkg/grpc" "github.com/e2b-dev/infra/packages/shared/pkg/grpc/orchestrator" "github.com/e2b-dev/infra/packages/shared/pkg/logger" + "github.com/e2b-dev/infra/packages/shared/pkg/models" "github.com/e2b-dev/infra/packages/shared/pkg/smap" ) diff --git a/packages/orchestrator/internal/server/sandboxes.go b/packages/orchestrator/internal/server/sandboxes.go index aa73f2114..eec5923ca 100644 --- a/packages/orchestrator/internal/server/sandboxes.go +++ b/packages/orchestrator/internal/server/sandboxes.go @@ -16,8 +16,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" "github.com/e2b-dev/infra/packages/orchestrator/internal/consul" - "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" - dbsandbox "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" + "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/database" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/build" "github.com/e2b-dev/infra/packages/shared/pkg/grpc/orchestrator" @@ -73,12 +72,14 @@ func (s *server) Create(ctxConn context.Context, req *orchestrator.SandboxCreate started := time.Now() s.sandboxes.Insert(req.Sandbox.SandboxId, sbx) - s.db.CreateSandbox(ctx, func(sc *models.SandboxCreate) { - sc.SetID(req.Sandbox.SandboxId) - sc.SetStatus(dbsandbox.Status(dbsandbox.StatusRunning)) - sc.SetStartedAt(started) - sc.SetDeadline(req.EndTime.AsTime()) - }) + if err := s.db.CreateSandbox(ctx, database.CreateSandboxParams{ + ID: req.Sandbox.SandboxId, + Status: database.SandboxStatusRunning, + StartedAt: started, + Deadline: req.EndTime.AsTime(), + }); err != nil { + return nil, err + } go func() { if err := sbx.Wait(); err != nil { @@ -91,12 +92,8 @@ func (s *server) Create(ctxConn context.Context, req *orchestrator.SandboxCreate } s.sandboxes.Remove(req.Sandbox.SandboxId) - if err := s.db.UpdateSandbox(ctx, req.Sandbox.SandboxId, func(sbu *models.SandboxUpdateOne) { - sbu.SetStatus(dbsandbox.StatusTerminated). - SetTerminatedAt(time.Now().Round(time.Millisecond)). - SetDurationMs(ended.Sub(started).Milliseconds()) - }); err != nil { - sbxlogger.E(sbx).Info("failed to cleanup db record for sandbox", zap.Error(err)) + if err := s.db.SetSandboxTerminated(ctx, req.Sandbox.SandboxId, ended.Sub(started)); err != nil { + sbxlogger.I(sbx).Error("failed to cleanup db record for sandbox", zap.Error(err)) } sbxlogger.E(sbx).Info("sandbox killed") @@ -125,10 +122,7 @@ func (s *server) Update(ctx context.Context, req *orchestrator.SandboxUpdateRequ } item.EndAt = req.EndTime.AsTime() - - if err := s.db.UpdateSandbox(ctx, req.SandboxId, func(sbu *models.SandboxUpdateOne) { - sbu.SetDeadline(item.EndAt) - }); err != nil { + if err := s.db.UpdateSandboxDeadline(ctx, req.SandboxId, item.EndAt); err != nil { return nil, status.New(codes.Internal, fmt.Sprintf("db update sandbox: %w", err)).Err() } @@ -201,17 +195,15 @@ func (s *server) Delete(ctxConn context.Context, in *orchestrator.SandboxDeleteR sbx.Healthcheck(loggingCtx, true) sbx.LogMetrics(loggingCtx) - if err := s.db.UpdateSandbox(ctx, in.SandboxId, func(sbu *models.SandboxUpdateOne) { - sbu.SetTerminatedAt(time.Now()).SetStatus(dbsandbox.StatusTerminated) - }); err != nil { - fmt.Fprintf(os.Stderr, "error setting sandbox deleted '%s': %v\n", in.SandboxId, err) - } - err := sbx.Stop() if err != nil { sbxlogger.I(sbx).Error("error stopping sandbox", zap.String("sandbox_id", in.SandboxId), zap.Error(err)) } + if err := s.db.SetSandboxTerminated(ctx, in.SandboxId, sbx.EndAt.Sub(sbx.StartedAt)); err != nil { + sbxlogger.I(sbx).Error("error setting sandbox deleted", zap.String("sandbox_id", in.SandboxId), zap.Error(err)) + } + return &emptypb.Empty{}, nil } @@ -248,11 +240,8 @@ func (s *server) Pause(ctx context.Context, in *orchestrator.SandboxPauseRequest s.dns.Remove(in.SandboxId, sbx.Slot.HostIP()) s.sandboxes.Remove(in.SandboxId) - if err := s.db.UpdateSandbox(ctx, in.SandboxId, func(sbu *models.SandboxUpdateOne) { - // TODO: either stop accounting for duration or update duration in the wrapper. - sbu.SetDurationMs(time.Now().Sub(sbx.StartedAt).Milliseconds()).SetStatus(dbsandbox.StatusPaused) - }); err != nil { - fmt.Fprintf(os.Stderr, "error setting sandbox deleted '%s': %v\n", in.SandboxId, err) + if err := s.db.SetSandboxPaused(ctx, in.SandboxId, time.Now().Sub(sbx.StartedAt)); err != nil { + sbxlogger.I(sbx).Error("error setting sandbox deleted", zap.String("sandbox_id", in.SandboxId), zap.Error(err)) } s.pauseMu.Unlock() diff --git a/packages/orchestrator/queries.sql b/packages/orchestrator/queries.sql new file mode 100644 index 000000000..cdc8a96eb --- /dev/null +++ b/packages/orchestrator/queries.sql @@ -0,0 +1,53 @@ +-- name: GlobalVersion :one +SELECT version FROM status WHERE id = 1; + +-- name: IncGlobalVersion :one +UPDATE status +SET + version = version + 1, + updated_at = current_timestamp() +WHERE + id = 1 +RETURNING version; + +-- name: SetGlobalStatus :one +UPDATE status +SET + version = version + 1, + updated_at = current_timestamp(), + status = sqlc.arg('status') +WHERE + id = 1 +RETURNING version; + +-- name: CreateSandbox :exec +INSERT INTO sandboxes(id, status, started_at, deadline, global_version) +VALUES ( + sqlc.arg('id'), + sqlc.arg('status'), + sqlc.arg('started_at'), + sqlc.arg('deadline'), + (SELECT version FROM status WHERE status.id = 1) +); + +-- name: ShutdownSandbox :exec +UPDATE sandboxes +SET + version = version + 1, + global_version = (SELECT version FROM status WHERE status.id = 1), + updated_at = current_timestamp(), + duration_ms = sqlc.arg('duration_ms'), + status = sqlc.arg('status') +WHERE + sandboxes.id = sqlc.arg('id'); + +-- name: UpdateSandboxDeadline :exec +UPDATE sandboxes +SET + version = version + 1, + global_version = (SELECT version FROM status WHERE status.id = 1), + udpated_at = current_timestamp(), + deadline = sqlc.arg('deadline'), + status = 'running' +WHERE + sandboxes.id = sqlc.arg('id'); diff --git a/packages/orchestrator/schema.sql b/packages/orchestrator/schema.sql new file mode 100644 index 000000000..950badf9c --- /dev/null +++ b/packages/orchestrator/schema.sql @@ -0,0 +1,27 @@ +PRAGMA integrity_check; +PRAGMA foreign_keys = ON; + +CREATE TABLE sandboxes ( + id TEXT PRIMARY KEY NOT NULL, + started_at TIMESTAMP NOT NULL DEFAULT current_timestamp, + updated_at TIMESTAMP NOT NULL DEFAULT current_timestamp, + deadline TIMESTAMP NOT NULL, + status TEXT CHECK( status IN ('pending', 'running', 'paused', 'terminated')) + NOT NULL DEFAULT 'pending', + duration_ms INTEGER CHECK( duration_ms > 0 ) + NOT NULL, + version INTEGER CHECK( version > 0 ) + NOT NULL, + global_version INTEGER CHECK( global_version > 0 ) + NOT NULL +); + +CREATE TABLE status ( + id INTEGER PRIMARY KEY NOT NULL, + version INTEGER NOT NULL DEFAULT 0, + updated_at TIMESTAMP NOT NULL DEFAULT current_timestamp, + status TEXT CHECK( status IN ('initializing', 'running', 'draining', 'quarantined ', 'terminated')) + NOT NULL DEFAULT 'running' +); + +INSERT INTO status(id) VALUES(1); diff --git a/sqlc.yaml b/sqlc.yaml new file mode 100644 index 000000000..615050b78 --- /dev/null +++ b/sqlc.yaml @@ -0,0 +1,24 @@ +version: "2" +sql: + # ORCHESTRATOR PROCESS' LOCAL DATABASE + - engine: "sqlite" + queries: "packages/orchestrator/queries.sql" + schema: "packages/orchestrator/schema.sql" + # migrations are unnecessary right now because the DB never lives + # longer than the process. + gen: + go: + emit_pointers_for_null_types: true + package: "database" + out: "packages/orchestrator/internal/pkg/database" + overrides: + - db_type: "timestamp" + go_type: + import: "time" + type: "time.Time" + - db_type: "timestamp" + nullable: true + go_type: + import: "time" + type: "time.Time" + pointer: true From ac9cedc384fc63d774e6345a006bf633c5edb7dd Mon Sep 17 00:00:00 2001 From: tycho garen Date: Fri, 7 Mar 2025 08:27:12 -0500 Subject: [PATCH 03/10] feat: track state machine for of orchestrator status (cherry picked from commit efefde48e1393ca523d164102835602374334395) --- packages/orchestrator/internal/db/db.go | 15 ++++++--- .../internal/pkg/database/queries.sql.go | 32 +++++++++++++------ packages/orchestrator/internal/server/main.go | 15 +++++---- packages/orchestrator/main.go | 4 +-- packages/orchestrator/queries.sql | 22 +++++++++---- packages/orchestrator/schema.sql | 2 +- 6 files changed, 60 insertions(+), 30 deletions(-) diff --git a/packages/orchestrator/internal/db/db.go b/packages/orchestrator/internal/db/db.go index 7a18160c9..a9231060c 100644 --- a/packages/orchestrator/internal/db/db.go +++ b/packages/orchestrator/internal/db/db.go @@ -16,11 +16,18 @@ type DB struct { ops *database.Queries } -func (db *DB) Close() error { - // TODO write terminated state to the status table for - // forensics(?) +func New(ctx context.Context, client *sql.DB) (*DB, error) { + db := &DB{client: client, ops: database.New(client)} - return db.client.Close() + if err := db.ops.SetOrchestratorStatusRunning(ctx); err != nil { + return nil, err + } + + return db, nil +} + +func (db *DB) Close(ctx context.Context) error { + return errors.Join(db.ops.SetOrchestratorStatusTerminated(ctx), db.client.Close()) } func (db *DB) CreateSandbox(ctx context.Context, params database.CreateSandboxParams) error { diff --git a/packages/orchestrator/internal/pkg/database/queries.sql.go b/packages/orchestrator/internal/pkg/database/queries.sql.go index 42ae14176..5e94677b5 100644 --- a/packages/orchestrator/internal/pkg/database/queries.sql.go +++ b/packages/orchestrator/internal/pkg/database/queries.sql.go @@ -55,7 +55,7 @@ SET version = version + 1, updated_at = current_timestamp() WHERE - id = 1 + id = 1 AND status != 'terminated' RETURNING version ` @@ -66,22 +66,34 @@ func (q *Queries) IncGlobalVersion(ctx context.Context) (int64, error) { return version, err } -const setGlobalStatus = `-- name: SetGlobalStatus :one +const setOrchestratorStatusRunning = `-- name: SetOrchestratorStatusRunning :exec UPDATE status SET version = version + 1, updated_at = current_timestamp(), - status = ?1 + status = 'running' WHERE - id = 1 -RETURNING version + id = 1 AND status = 'initializing' ` -func (q *Queries) SetGlobalStatus(ctx context.Context, status string) (int64, error) { - row := q.db.QueryRowContext(ctx, setGlobalStatus, status) - var version int64 - err := row.Scan(&version) - return version, err +func (q *Queries) SetOrchestratorStatusRunning(ctx context.Context) error { + _, err := q.db.ExecContext(ctx, setOrchestratorStatusRunning) + return err +} + +const setOrchestratorStatusTerminated = `-- name: SetOrchestratorStatusTerminated :exec +UPDATE status +SET + version = version + 1, + updated_at = current_timestamp(), + status = 'terminated' +WHERE + id = 1 AND status != 'terminated' +` + +func (q *Queries) SetOrchestratorStatusTerminated(ctx context.Context) error { + _, err := q.db.ExecContext(ctx, setOrchestratorStatusTerminated) + return err } const shutdownSandbox = `-- name: ShutdownSandbox :exec diff --git a/packages/orchestrator/internal/server/main.go b/packages/orchestrator/internal/server/main.go index 0c9f44f64..bc535ad68 100644 --- a/packages/orchestrator/internal/server/main.go +++ b/packages/orchestrator/internal/server/main.go @@ -2,6 +2,7 @@ package server import ( "context" + "database/sql" "errors" "fmt" "math" @@ -20,8 +21,8 @@ import ( "google.golang.org/grpc/health" "google.golang.org/grpc/health/grpc_health_v1" - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql" + // "entgo.io/ent/dialect" + // "entgo.io/ent/dialect/sql" "github.com/e2b-dev/infra/packages/orchestrator/internal/db" "github.com/e2b-dev/infra/packages/orchestrator/internal/dns" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox" @@ -30,7 +31,6 @@ import ( e2bgrpc "github.com/e2b-dev/infra/packages/shared/pkg/grpc" "github.com/e2b-dev/infra/packages/shared/pkg/grpc/orchestrator" "github.com/e2b-dev/infra/packages/shared/pkg/logger" - "github.com/e2b-dev/infra/packages/shared/pkg/models" "github.com/e2b-dev/infra/packages/shared/pkg/smap" ) @@ -53,7 +53,7 @@ type Service struct { grpc *grpc.Server dns *dns.DNS port uint16 - db *models.Client + db *db.DB started atomic.Bool shutdown struct { once sync.Once @@ -117,12 +117,15 @@ func New(ctx context.Context, port uint) (*Service, error) { // BLOCK: setup database { const dbConnStr = "file:./db/sandboxes.db?_journal_mode=wal" - drv, err := sql.Open(dialect.SQLite, dbConnStr) + drv, err := sql.Open("sqlite3", dbConnStr) if err != nil { return nil, fmt.Errorf("connecting to %q: %w", dbConnStr, err) } - srv.db = models.NewClient(models.Driver(drv)) + srv.db, err = db.New(drv) + if err != nil { + return nil, fmt.Errorf("using database at %q: %w", dbConnStr, err) + } } orchestrator.RegisterSandboxServiceServer(srv.grpc, srv.server) diff --git a/packages/orchestrator/main.go b/packages/orchestrator/main.go index e613ef7dc..8f5c3f897 100644 --- a/packages/orchestrator/main.go +++ b/packages/orchestrator/main.go @@ -93,11 +93,11 @@ func main() { defer sbxLoggerInternal.Sync() sbxlogger.SetSandboxLoggerInternal(sbxLoggerInternal) - log.Println("Starting orchestrator", "commit", commitSHA) + logger.Info("Starting orchestrator", zap.String("commit", commitSHA)) srv, err := server.New(ctx, port) if err != nil { - zap.L().Fatal("failed to create server", zap.Error(err)) + zap.L().Panic("failed to create server", zap.Error(err)) } wg.Add(1) diff --git a/packages/orchestrator/queries.sql b/packages/orchestrator/queries.sql index cdc8a96eb..1b5510858 100644 --- a/packages/orchestrator/queries.sql +++ b/packages/orchestrator/queries.sql @@ -1,23 +1,31 @@ -- name: GlobalVersion :one SELECT version FROM status WHERE id = 1; --- name: IncGlobalVersion :one +-- name: SetOrchestratorStatusRunning :exec UPDATE status SET version = version + 1, - updated_at = current_timestamp() + updated_at = current_timestamp(), + status = 'running' WHERE - id = 1 -RETURNING version; + id = 1 AND status = 'initializing'; --- name: SetGlobalStatus :one +-- name: SetOrchestratorStatusTerminated :exec UPDATE status SET version = version + 1, updated_at = current_timestamp(), - status = sqlc.arg('status') + status = 'terminated' +WHERE + id = 1 AND status != 'terminated'; + +-- name: IncGlobalVersion :one +UPDATE status +SET + version = version + 1, + updated_at = current_timestamp() WHERE - id = 1 + id = 1 AND status != 'terminated' RETURNING version; -- name: CreateSandbox :exec diff --git a/packages/orchestrator/schema.sql b/packages/orchestrator/schema.sql index 950badf9c..d8ff0a596 100644 --- a/packages/orchestrator/schema.sql +++ b/packages/orchestrator/schema.sql @@ -21,7 +21,7 @@ CREATE TABLE status ( version INTEGER NOT NULL DEFAULT 0, updated_at TIMESTAMP NOT NULL DEFAULT current_timestamp, status TEXT CHECK( status IN ('initializing', 'running', 'draining', 'quarantined ', 'terminated')) - NOT NULL DEFAULT 'running' + NOT NULL DEFAULT 'initializing' ); INSERT INTO status(id) VALUES(1); From d17e5d4e61cf2a312ce634d77e3abeb3a7860258 Mon Sep 17 00:00:00 2001 From: tycho garen Date: Fri, 7 Mar 2025 08:27:58 -0500 Subject: [PATCH 04/10] fix: remove unneeded imports (cherry picked from commit e0bdcf8c800ec56397ea5e66fba80f152d9352e5) --- packages/orchestrator/internal/server/main.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/orchestrator/internal/server/main.go b/packages/orchestrator/internal/server/main.go index bc535ad68..72337ed76 100644 --- a/packages/orchestrator/internal/server/main.go +++ b/packages/orchestrator/internal/server/main.go @@ -21,8 +21,6 @@ import ( "google.golang.org/grpc/health" "google.golang.org/grpc/health/grpc_health_v1" - // "entgo.io/ent/dialect" - // "entgo.io/ent/dialect/sql" "github.com/e2b-dev/infra/packages/orchestrator/internal/db" "github.com/e2b-dev/infra/packages/orchestrator/internal/dns" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox" From f554c70b56962346180908d139e42c4bd5bc2783 Mon Sep 17 00:00:00 2001 From: tycho garen Date: Thu, 27 Mar 2025 16:50:44 -0400 Subject: [PATCH 05/10] fix compiles and add sandbox configs to orchestrator database --- Makefile | 13 +--- packages/orchestrator/Makefile | 4 +- packages/orchestrator/internal/makefile | 4 -- .../internal/pkg/database/models.go | 1 + .../internal/pkg/database/queries.sql.go | 5 +- .../internal/server/healthcheck.go | 5 +- .../orchestrator/internal/server/sandboxes.go | 65 ++++++++++--------- packages/orchestrator/queries.sql | 3 +- packages/orchestrator/schema.sql | 3 +- 9 files changed, 51 insertions(+), 52 deletions(-) delete mode 100644 packages/orchestrator/internal/makefile diff --git a/Makefile b/Makefile index 9426e3e89..94b088028 100644 --- a/Makefile +++ b/Makefile @@ -130,14 +130,6 @@ migrate: # $(MAKE) -C packages/shared migrate-clickhouse/up -.PHONY: generate -generate: -generate/%: - $(MAKE) -C packages/$(notdir $@) generate - @printf "\n\n" - - - .PHONY: generate generate:generate/api generate:generate/orchestrator @@ -147,8 +139,9 @@ generate:generate/db generate:generate/orchestrator/internal generate:generate/shared generate/%: - @echo "Generating code for *$(notdir $@)*" - $(MAKE) -C packages/$(subst generate/,,$@) generate-models + $(MAKE) -C packages/$(notdir $@) generate + @printf "\n\n" + .PHONY: switch-env switch-env: diff --git a/packages/orchestrator/Makefile b/packages/orchestrator/Makefile index 6d37794b2..c02e64678 100644 --- a/packages/orchestrator/Makefile +++ b/packages/orchestrator/Makefile @@ -10,10 +10,10 @@ init: go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2 .PHONY: generate -generate: +generate:generate-models # You need to install protobuf (brew install protobuf) and following go packages: protoc-gen-go, protoc-gen-go-grpc # https://grpc.io/docs/languages/go/quickstart/ - @echo "Generating..." + @echo "Generating protoc..." @protoc --go_out=../shared/pkg/grpc/orchestrator/ --go_opt=paths=source_relative --go-grpc_out=../shared/pkg/grpc/orchestrator/ --go-grpc_opt=paths=source_relative orchestrator.proto @echo "Done" diff --git a/packages/orchestrator/internal/makefile b/packages/orchestrator/internal/makefile deleted file mode 100644 index 807aa0b6e..000000000 --- a/packages/orchestrator/internal/makefile +++ /dev/null @@ -1,4 +0,0 @@ -.PHONY: generate-models -generate-models: - rm -rf pkg/models/* - go generate ./pkg/generate_models.go diff --git a/packages/orchestrator/internal/pkg/database/models.go b/packages/orchestrator/internal/pkg/database/models.go index 8ff01c5f5..ed2927e41 100644 --- a/packages/orchestrator/internal/pkg/database/models.go +++ b/packages/orchestrator/internal/pkg/database/models.go @@ -17,6 +17,7 @@ type Sandbox struct { DurationMs int64 Version int64 GlobalVersion int64 + Config []byte } type Status struct { diff --git a/packages/orchestrator/internal/pkg/database/queries.sql.go b/packages/orchestrator/internal/pkg/database/queries.sql.go index 5e94677b5..e50a5bd12 100644 --- a/packages/orchestrator/internal/pkg/database/queries.sql.go +++ b/packages/orchestrator/internal/pkg/database/queries.sql.go @@ -11,12 +11,13 @@ import ( ) const createSandbox = `-- name: CreateSandbox :exec -INSERT INTO sandboxes(id, status, started_at, deadline, global_version) +INSERT INTO sandboxes(id, status, started_at, deadline, config, global_version) VALUES ( ?1, ?2, ?3, ?4, + ?5, (SELECT version FROM status WHERE status.id = 1) ) ` @@ -26,6 +27,7 @@ type CreateSandboxParams struct { Status string StartedAt time.Time Deadline time.Time + Config []byte } func (q *Queries) CreateSandbox(ctx context.Context, arg CreateSandboxParams) error { @@ -34,6 +36,7 @@ func (q *Queries) CreateSandbox(ctx context.Context, arg CreateSandboxParams) er arg.Status, arg.StartedAt, arg.Deadline, + arg.Config, ) return err } diff --git a/packages/orchestrator/internal/server/healthcheck.go b/packages/orchestrator/internal/server/healthcheck.go index 483baf5f3..b611742a7 100644 --- a/packages/orchestrator/internal/server/healthcheck.go +++ b/packages/orchestrator/internal/server/healthcheck.go @@ -81,14 +81,13 @@ func (h *Healthcheck) Start(ctx context.Context, listener net.Listener) error { } }() - - shutdownErr := make(chan err) + shutdownErr := make(chan error) go func() { defer close(shutdownErr) <-ctx.Done() shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second) - defer shutdownCtx + defer shutdownCancel() if err := httpServer.Shutdown(shutdownCtx); err != nil { select { diff --git a/packages/orchestrator/internal/server/sandboxes.go b/packages/orchestrator/internal/server/sandboxes.go index d69641f1d..6c4f4636e 100644 --- a/packages/orchestrator/internal/server/sandboxes.go +++ b/packages/orchestrator/internal/server/sandboxes.go @@ -11,8 +11,9 @@ import ( "go.opentelemetry.io/otel/attribute" "go.uber.org/zap" "golang.org/x/sync/semaphore" + "google.golang.org/grpc" "google.golang.org/grpc/codes" - "google.golang.org/grpc/internal/status" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/timestamppb" @@ -68,20 +69,26 @@ func (s *server) Create(ctxConn context.Context, req *orchestrator.SandboxCreate if err != nil { zap.L().Error("failed to create sandbox, cleaning up", zap.Error(err)) cleanupErr := cleanup.Run() + err = grpc.Errorf(codes.Internal, "failed to cleanup sandbox: %w", errors.Join(err, context.Cause(ctx), cleanupErr)) - errMsg := fmt.Errorf("failed to cleanup sandbox: %w", errors.Join(err, context.Cause(ctx), cleanupErr)) - telemetry.ReportCriticalError(ctx, errMsg) + telemetry.ReportCriticalError(ctx, err) - return nil, status.New(codes.Internal, err.Error()).Err() + return nil, err } started := time.Now() + confProto, err := proto.Marshal(sbx.Config) + if err != nil { + sbxlogger.I(sbx).Error("failed to marshal sandbox config for the database", zap.Error(err)) + } + s.sandboxes.Insert(req.Sandbox.SandboxId, sbx) if err := s.db.CreateSandbox(ctx, database.CreateSandboxParams{ ID: req.Sandbox.SandboxId, Status: database.SandboxStatusRunning, StartedAt: started, Deadline: req.EndTime.AsTime(), + Config: confProto, }); err != nil { return nil, err } @@ -134,15 +141,14 @@ func (s *server) Update(ctx context.Context, req *orchestrator.SandboxUpdateRequ item, ok := s.sandboxes.Get(req.SandboxId) if !ok { - errMsg := fmt.Errorf("sandbox not found") - telemetry.ReportCriticalError(ctx, errMsg) - - return nil, status.New(codes.NotFound, errMsg.Error()).Err() + err := grpc.Errorf(codes.NotFound, "sandbox not found") + telemetry.ReportCriticalError(ctx, err) + return nil, err } item.EndAt = req.EndTime.AsTime() if err := s.db.UpdateSandboxDeadline(ctx, req.SandboxId, item.EndAt); err != nil { - return nil, status.New(codes.Internal, fmt.Sprintf("db update sandbox: %w", err)).Err() + return nil, grpc.Errorf(codes.Internal, fmt.Sprintf("db update sandbox: %w", err)) } return &emptypb.Empty{}, nil @@ -192,10 +198,10 @@ func (s *server) Delete(ctxConn context.Context, in *orchestrator.SandboxDeleteR sbx, ok := s.sandboxes.Get(in.SandboxId) if !ok { - errMsg := fmt.Errorf("sandbox '%s' not found", in.SandboxId) - telemetry.ReportCriticalError(ctx, errMsg) + err := fmt.Errorf("sandbox '%s' not found", in.SandboxId) + telemetry.ReportCriticalError(ctx, err) - return nil, status.New(codes.NotFound, errMsg.Error()).Err() + return nil, grpc.Errorf(codes.NotFound, err.Error()) } // Don't allow connecting to the sandbox anymore. @@ -237,7 +243,7 @@ func (s *server) Pause(ctx context.Context, in *orchestrator.SandboxPauseRequest if err != nil { telemetry.ReportCriticalError(ctx, err) - return nil, status.New(codes.ResourceExhausted, err.Error()).Err() + return nil, grpc.Errorf(codes.ResourceExhausted, err.Error()) } releaseOnce := sync.OnceFunc(func() { @@ -251,10 +257,10 @@ func (s *server) Pause(ctx context.Context, in *orchestrator.SandboxPauseRequest if !ok { s.pauseMu.Unlock() - errMsg := fmt.Errorf("sandbox not found") - telemetry.ReportCriticalError(ctx, errMsg) + err := fmt.Errorf("sandbox not found") + telemetry.ReportCriticalError(ctx, err) - return nil, status.New(codes.NotFound, errMsg.Error()).Err() + return nil, grpc.Errorf(codes.NotFound, err.Error()) } s.dns.Remove(in.SandboxId, sbx.Slot.HostIP()) @@ -274,18 +280,17 @@ func (s *server) Pause(ctx context.Context, in *orchestrator.SandboxPauseRequest sbx.Config.HugePages, ).NewTemplateCacheFiles() if err != nil { - errMsg := fmt.Errorf("error creating template files: %w", err) - telemetry.ReportCriticalError(ctx, errMsg) + err = fmt.Errorf("error creating template files: %w", err) + telemetry.ReportCriticalError(ctx, err) - return nil, status.New(codes.Internal, errMsg.Error()).Err() + return nil, grpc.Errorf(codes.Internal, err.Error()) } defer func() { // sbx.Stop sometimes blocks for several seconds, // so we don't want to block the request and do the cleanup in a goroutine after we already removed sandbox from cache and DNS. go func() { - err := sbx.Stop() - if err != nil { + if err := sbx.Stop(); err != nil { sbxlogger.I(sbx).Error("error stopping sandbox after snapshot", zap.String("sandbox_id", in.SandboxId), zap.Error(err)) } }() @@ -293,18 +298,18 @@ func (s *server) Pause(ctx context.Context, in *orchestrator.SandboxPauseRequest err = os.MkdirAll(snapshotTemplateFiles.CacheDir(), 0o755) if err != nil { - errMsg := fmt.Errorf("error creating sandbox cache dir '%s': %w", snapshotTemplateFiles.CacheDir(), err) - telemetry.ReportCriticalError(ctx, errMsg) + err = fmt.Errorf("error creating sandbox cache dir '%s': %w", snapshotTemplateFiles.CacheDir(), err) + telemetry.ReportCriticalError(ctx, err) - return nil, status.New(codes.Internal, errMsg.Error()).Err() + return nil, grpc.Errorf(codes.Internal, err.Error()) } snapshot, err := sbx.Snapshot(ctx, s.tracer, snapshotTemplateFiles, releaseOnce) if err != nil { - errMsg := fmt.Errorf("error snapshotting sandbox '%s': %w", in.SandboxId, err) - telemetry.ReportCriticalError(ctx, errMsg) + err = fmt.Errorf("error snapshotting sandbox '%s': %w", in.SandboxId, err) + telemetry.ReportCriticalError(ctx, err) - return nil, status.New(codes.Internal, errMsg.Error()).Err() + return nil, grpc.Errorf(codes.Internal, err.Error()) } err = s.templateCache.AddSnapshot( @@ -320,10 +325,10 @@ func (s *server) Pause(ctx context.Context, in *orchestrator.SandboxPauseRequest snapshot.RootfsDiff, ) if err != nil { - errMsg := fmt.Errorf("error adding snapshot to template cache: %w", err) - telemetry.ReportCriticalError(ctx, errMsg) + err = fmt.Errorf("error adding snapshot to template cache: %w", err) + telemetry.ReportCriticalError(ctx, err) - return nil, status.New(codes.Internal, errMsg.Error()).Err() + return nil, grpc.Errorf(codes.Internal, err.Error()) } telemetry.ReportEvent(ctx, "added snapshot to template cache") diff --git a/packages/orchestrator/queries.sql b/packages/orchestrator/queries.sql index 1b5510858..d430a5aae 100644 --- a/packages/orchestrator/queries.sql +++ b/packages/orchestrator/queries.sql @@ -29,12 +29,13 @@ WHERE RETURNING version; -- name: CreateSandbox :exec -INSERT INTO sandboxes(id, status, started_at, deadline, global_version) +INSERT INTO sandboxes(id, status, started_at, deadline, config, global_version) VALUES ( sqlc.arg('id'), sqlc.arg('status'), sqlc.arg('started_at'), sqlc.arg('deadline'), + sqlc.arg('config'), (SELECT version FROM status WHERE status.id = 1) ); diff --git a/packages/orchestrator/schema.sql b/packages/orchestrator/schema.sql index d8ff0a596..b80149610 100644 --- a/packages/orchestrator/schema.sql +++ b/packages/orchestrator/schema.sql @@ -13,7 +13,8 @@ CREATE TABLE sandboxes ( version INTEGER CHECK( version > 0 ) NOT NULL, global_version INTEGER CHECK( global_version > 0 ) - NOT NULL + NOT NULL, + config BLOB ); CREATE TABLE status ( From 0aade1e8074d5e7837344cbb653cdc70ea63b69e Mon Sep 17 00:00:00 2001 From: tycho garen Date: Thu, 27 Mar 2025 17:05:59 -0400 Subject: [PATCH 06/10] code review feedback --- packages/orchestrator/internal/db/db.go | 2 - packages/orchestrator/internal/server/main.go | 143 +++++++++--------- 2 files changed, 70 insertions(+), 75 deletions(-) diff --git a/packages/orchestrator/internal/db/db.go b/packages/orchestrator/internal/db/db.go index a9231060c..c11793c24 100644 --- a/packages/orchestrator/internal/db/db.go +++ b/packages/orchestrator/internal/db/db.go @@ -7,8 +7,6 @@ import ( "time" "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/database" - // "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models" - // "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/models/sandbox" ) type DB struct { diff --git a/packages/orchestrator/internal/server/main.go b/packages/orchestrator/internal/server/main.go index 103d890ae..81dbc040c 100644 --- a/packages/orchestrator/internal/server/main.go +++ b/packages/orchestrator/internal/server/main.go @@ -104,95 +104,92 @@ func New(ctx context.Context, port uint, clientID string, version string, proxy } // BLOCK: initialize services - { - srv.dns = dns.New() - srv.proxy = proxy - - opts := []logging.Option{ - logging.WithLogOnEvents(logging.StartCall, logging.PayloadReceived, logging.PayloadSent, logging.FinishCall), - logging.WithLevels(logging.DefaultServerCodeToLevel), - logging.WithFieldsFromContext(logging.ExtractFields), - } - srv.grpc = grpc.NewServer( - grpc.StatsHandler(e2bgrpc.NewStatsWrapper(otelgrpc.NewServerHandler())), - grpc.ChainUnaryInterceptor( - recovery.UnaryServerInterceptor(), - selector.UnaryServerInterceptor( - logging.UnaryServerInterceptor(logger.GRPCLogger(zap.L()), opts...), - logger.WithoutHealthCheck(), - ), + srv.dns = dns.New() + srv.proxy = proxy + + opts := []logging.Option{ + logging.WithLogOnEvents(logging.StartCall, logging.PayloadReceived, logging.PayloadSent, logging.FinishCall), + logging.WithLevels(logging.DefaultServerCodeToLevel), + logging.WithFieldsFromContext(logging.ExtractFields), + } + srv.grpc = grpc.NewServer( + grpc.StatsHandler(e2bgrpc.NewStatsWrapper(otelgrpc.NewServerHandler())), + grpc.ChainUnaryInterceptor( + recovery.UnaryServerInterceptor(), + selector.UnaryServerInterceptor( + logging.UnaryServerInterceptor(logger.GRPCLogger(zap.L()), opts...), + logger.WithoutHealthCheck(), ), - grpc.ChainStreamInterceptor( - selector.StreamServerInterceptor( - logging.StreamServerInterceptor(logger.GRPCLogger(zap.L()), opts...), - logger.WithoutHealthCheck(), - ), + ), + grpc.ChainStreamInterceptor( + selector.StreamServerInterceptor( + logging.StreamServerInterceptor(logger.GRPCLogger(zap.L()), opts...), + logger.WithoutHealthCheck(), ), - ) + ), + ) - devicePool, err := nbd.NewDevicePool() + devicePool, err := nbd.NewDevicePool() - if err != nil { - return nil, fmt.Errorf("failed to create device pool: %w", err) - } + if err != nil { + return nil, fmt.Errorf("failed to create device pool: %w", err) + } - useLokiMetrics := os.Getenv("WRITE_LOKI_METRICS") - useClickhouseMetrics := os.Getenv("WRITE_CLICKHOUSE_METRICS") - readClickhouseMetrics := os.Getenv("READ_CLICKHOUSE_METRICS") - - var clickhouseStore chdb.Store = nil - - if readClickhouseMetrics == "true" || useClickhouseMetrics == "true" { - clickhouseStore, err = chdb.NewStore(chdb.ClickHouseConfig{ - ConnectionString: os.Getenv("CLICKHOUSE_CONNECTION_STRING"), - Username: os.Getenv("CLICKHOUSE_USERNAME"), - Password: os.Getenv("CLICKHOUSE_PASSWORD"), - Database: os.Getenv("CLICKHOUSE_DATABASE"), - Debug: os.Getenv("CLICKHOUSE_DEBUG") == "true", - }) - if err != nil { - return nil, fmt.Errorf("failed to create clickhouse store: %w", err) - } - } + useLokiMetrics := os.Getenv("WRITE_LOKI_METRICS") + useClickhouseMetrics := os.Getenv("WRITE_CLICKHOUSE_METRICS") + readClickhouseMetrics := os.Getenv("READ_CLICKHOUSE_METRICS") - srv.server = &server{ - tracer: otel.Tracer(ServiceName), - dns: srv.dns, - proxy: srv.proxy, - sandboxes: smap.New[*sandbox.Sandbox](), - networkPool: networkPool, - templateCache: templateCache, - clientID: clientID, - devicePool: devicePool, - clickhouseStore: clickhouseStore, - useLokiMetrics: useLokiMetrics, - useClickhouseMetrics: useClickhouseMetrics, - } - _, err = meters.GetObservableUpDownCounter(meters.OrchestratorSandboxCountMeterName, func(ctx context.Context, observer metric.Int64Observer) error { - observer.Observe(int64(srv.server.sandboxes.Count())) + var clickhouseStore chdb.Store = nil - return nil + if readClickhouseMetrics == "true" || useClickhouseMetrics == "true" { + clickhouseStore, err = chdb.NewStore(chdb.ClickHouseConfig{ + ConnectionString: os.Getenv("CLICKHOUSE_CONNECTION_STRING"), + Username: os.Getenv("CLICKHOUSE_USERNAME"), + Password: os.Getenv("CLICKHOUSE_PASSWORD"), + Database: os.Getenv("CLICKHOUSE_DATABASE"), + Debug: os.Getenv("CLICKHOUSE_DEBUG") == "true", }) - if err != nil { - zap.L().Error("Error registering sandbox count metric", zap.Any("metric_name", meters.OrchestratorSandboxCountMeterName), zap.Error(err)) + return nil, fmt.Errorf("failed to create clickhouse store: %w", err) } } + srv.server = &server{ + tracer: otel.Tracer(ServiceName), + dns: srv.dns, + proxy: srv.proxy, + sandboxes: smap.New[*sandbox.Sandbox](), + networkPool: networkPool, + templateCache: templateCache, + clientID: clientID, + devicePool: devicePool, + clickhouseStore: clickhouseStore, + useLokiMetrics: useLokiMetrics, + useClickhouseMetrics: useClickhouseMetrics, + } + _, err = meters.GetObservableUpDownCounter(meters.OrchestratorSandboxCountMeterName, func(ctx context.Context, observer metric.Int64Observer) error { + observer.Observe(int64(srv.server.sandboxes.Count())) + + return nil + }) + + if err != nil { + zap.L().Error("Error registering sandbox count metric", zap.Any("metric_name", meters.OrchestratorSandboxCountMeterName), zap.Error(err)) + } + // BLOCK: setup database - { - const dbConnStr = "file:./db/sandboxes.db?_journal_mode=wal" - drv, err := sql.Open("sqlite3", dbConnStr) - if err != nil { - return nil, fmt.Errorf("connecting to %q: %w", dbConnStr, err) - } + const dbConnStr = "file:./db/sandboxes.db?_journal_mode=wal" + drv, err := sql.Open("sqlite3", dbConnStr) + if err != nil { + return nil, fmt.Errorf("connecting to %q: %w", dbConnStr, err) + } - srv.db, err = db.New(ctx, drv) - if err != nil { - return nil, fmt.Errorf("using database at %q: %w", dbConnStr, err) - } + srv.db, err = db.New(ctx, drv) + if err != nil { + return nil, fmt.Errorf("using database at %q: %w", dbConnStr, err) } + // BLOCK: register services and return orchestrator.RegisterSandboxServiceServer(srv.grpc, srv.server) srv.grpcHealth = health.NewServer() From a7088deab677c88ed443d9f437537b4a7ca6c0a1 Mon Sep 17 00:00:00 2001 From: tycho garen Date: Thu, 27 Mar 2025 18:43:25 -0400 Subject: [PATCH 07/10] clean up checks --- packages/orchestrator/internal/sandbox/checks.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/orchestrator/internal/sandbox/checks.go b/packages/orchestrator/internal/sandbox/checks.go index c244a1bf2..3d4dbdcea 100644 --- a/packages/orchestrator/internal/sandbox/checks.go +++ b/packages/orchestrator/internal/sandbox/checks.go @@ -98,14 +98,14 @@ func (s *Sandbox) Healthcheck(ctx context.Context, alwaysReport bool) { address := fmt.Sprintf("http://%s:%d/health", s.Slot.HostIP(), consts.DefaultEnvdServerPort) - var request *http.Request - + var request *http.Request // declare before use rather than := so that the defer works request, err = http.NewRequestWithContext(ctx, "GET", address, nil) if err != nil { return } - response, err := httpClient.Do(request) + var response *http.Response // declare before use rather than := so that the defer works + response, err = httpClient.Do(request) if err != nil { return } @@ -123,6 +123,7 @@ func (s *Sandbox) Healthcheck(ctx context.Context, alwaysReport bool) { return } + // additional checks as needed ... } func isGTEVersion(curVersion, minVersion string) bool { From 49759a4726fbf0df0889ac8f3b80cd6e3028a0f8 Mon Sep 17 00:00:00 2001 From: Sam Kleinman Date: Wed, 2 Apr 2025 16:32:46 -0400 Subject: [PATCH 08/10] Update packages/orchestrator/Makefile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jakub Novák --- packages/orchestrator/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/orchestrator/Makefile b/packages/orchestrator/Makefile index c02e64678..eb70b284e 100644 --- a/packages/orchestrator/Makefile +++ b/packages/orchestrator/Makefile @@ -10,7 +10,7 @@ init: go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2 .PHONY: generate -generate:generate-models +generate: # You need to install protobuf (brew install protobuf) and following go packages: protoc-gen-go, protoc-gen-go-grpc # https://grpc.io/docs/languages/go/quickstart/ @echo "Generating protoc..." From 608adc6f12c4cb1561d8dfc18d5410ca1f3a6298 Mon Sep 17 00:00:00 2001 From: tycho garen Date: Thu, 3 Apr 2025 14:08:07 -0400 Subject: [PATCH 09/10] feat: process should initialize the database schema --- packages/orchestrator/internal/db/db.go | 9 +++++++++ packages/orchestrator/internal/server/main.go | 2 ++ packages/orchestrator/main.go | 13 ++++++++++--- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/packages/orchestrator/internal/db/db.go b/packages/orchestrator/internal/db/db.go index c11793c24..c27097c63 100644 --- a/packages/orchestrator/internal/db/db.go +++ b/packages/orchestrator/internal/db/db.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "errors" + "fmt" "time" "github.com/e2b-dev/infra/packages/orchestrator/internal/pkg/database" @@ -24,6 +25,14 @@ func New(ctx context.Context, client *sql.DB) (*DB, error) { return db, nil } +func (db *DB) Init(ctx context.Context, ddl string) error { + if _, err := db.client.ExecContext(ctx, ddl); err != nil { + return fmt.Errorf("problem initializing the database: %w", err) + } + + return nil +} + func (db *DB) Close(ctx context.Context) error { return errors.Join(db.ops.SetOrchestratorStatusTerminated(ctx), db.client.Close()) } diff --git a/packages/orchestrator/internal/server/main.go b/packages/orchestrator/internal/server/main.go index 81dbc040c..d713a0ad2 100644 --- a/packages/orchestrator/internal/server/main.go +++ b/packages/orchestrator/internal/server/main.go @@ -300,6 +300,8 @@ func (srv *Service) Start(ctx context.Context) error { return nil } +func (srv *Service) SetupDB(ctx context.Context, ddl string) error { return srv.db.Init(ctx, ddl) } + func (srv *Service) Close(ctx context.Context) error { srv.shutdown.once.Do(func() { if srv.shutdown.op == nil { diff --git a/packages/orchestrator/main.go b/packages/orchestrator/main.go index a1eb980de..7c0325c8f 100644 --- a/packages/orchestrator/main.go +++ b/packages/orchestrator/main.go @@ -32,7 +32,10 @@ const ( var commitSHA string -func run() int32 { +//go:embed schema.sql +var ddl string + +func run() int { ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -109,6 +112,10 @@ func run() int32 { zap.L().Panic("failed to create server", zap.Error(err)) } + if err := srv.SetupDB(ctx, ddl); err != nil { + zap.L().Panic("failed database setup", zap.Error(err)) + } + wg.Add(1) go func() { defer wg.Done() @@ -180,9 +187,9 @@ func run() int32 { wg.Wait() - return exitCode.Load() + return int(exitCode.Load()) } func main() { - os.Exit(int(run())) + os.Exit(run()) } From 3727a6cf3486a4772e80ac8190d793abe9602996 Mon Sep 17 00:00:00 2001 From: tycho garen Date: Thu, 3 Apr 2025 17:55:21 -0400 Subject: [PATCH 10/10] orchestrator status report and test --- packages/orchestrator/go.mod | 1 + packages/orchestrator/go.sum | 2 + packages/orchestrator/internal/db/db.go | 24 +- .../{ => internal/db}/queries.sql | 24 +- .../orchestrator/{ => internal/db}/schema.sql | 10 +- .../internal/pkg/database/helpers.go | 44 ++ .../internal/pkg/database/queries.sql.go | 57 +- packages/orchestrator/internal/server/main.go | 46 +- .../orchestrator/internal/server/sandboxes.go | 69 +- .../internal/server/sandboxes_test.go | 84 +- packages/orchestrator/main.go | 19 +- packages/orchestrator/orchestrator.proto | 23 +- .../pkg/grpc/orchestrator/orchestrator.pb.go | 739 ++++++++---------- .../grpc/orchestrator/orchestrator_grpc.pb.go | 104 ++- sqlc.yaml | 4 +- 15 files changed, 741 insertions(+), 509 deletions(-) rename packages/orchestrator/{ => internal/db}/queries.sql (61%) rename packages/orchestrator/{ => internal/db}/schema.sql (77%) create mode 100644 packages/orchestrator/internal/pkg/database/helpers.go diff --git a/packages/orchestrator/go.mod b/packages/orchestrator/go.mod index a10b0b69e..1394cd478 100644 --- a/packages/orchestrator/go.mod +++ b/packages/orchestrator/go.mod @@ -98,6 +98,7 @@ require ( github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-sqlite3 v1.14.27 // indirect github.com/mdlayher/genetlink v1.3.2 // indirect github.com/mdlayher/netlink v1.7.2 // indirect github.com/mdlayher/socket v0.5.1 // indirect diff --git a/packages/orchestrator/go.sum b/packages/orchestrator/go.sum index 4d302ef76..56eb381be 100644 --- a/packages/orchestrator/go.sum +++ b/packages/orchestrator/go.sum @@ -688,6 +688,8 @@ github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y= +github.com/mattn/go-sqlite3 v1.14.27 h1:drZCnuvf37yPfs95E5jd9s3XhdVWLal+6BOK6qrv6IU= +github.com/mattn/go-sqlite3 v1.14.27/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/mdlayher/genetlink v1.3.2 h1:KdrNKe+CTu+IbZnm/GVUMXSqBBLqcGpRDa0xkQy56gw= diff --git a/packages/orchestrator/internal/db/db.go b/packages/orchestrator/internal/db/db.go index c27097c63..f5e6307fb 100644 --- a/packages/orchestrator/internal/db/db.go +++ b/packages/orchestrator/internal/db/db.go @@ -15,9 +15,13 @@ type DB struct { ops *database.Queries } -func New(ctx context.Context, client *sql.DB) (*DB, error) { +func New(ctx context.Context, client *sql.DB, schema string) (*DB, error) { db := &DB{client: client, ops: database.New(client)} + if _, err := db.client.ExecContext(ctx, schema); err != nil { + return nil, fmt.Errorf("problem initializing the database: %w", err) + } + if err := db.ops.SetOrchestratorStatusRunning(ctx); err != nil { return nil, err } @@ -25,18 +29,20 @@ func New(ctx context.Context, client *sql.DB) (*DB, error) { return db, nil } -func (db *DB) Init(ctx context.Context, ddl string) error { - if _, err := db.client.ExecContext(ctx, ddl); err != nil { - return fmt.Errorf("problem initializing the database: %w", err) - } - - return nil -} - func (db *DB) Close(ctx context.Context) error { return errors.Join(db.ops.SetOrchestratorStatusTerminated(ctx), db.client.Close()) } +func (db *DB) Status(ctx context.Context) (*database.OrchestratorStatusRow, error) { + report, err := db.ops.OrchestratorStatus(ctx) + if err != nil { + return nil, err + } + out := report + + return &out, nil +} + func (db *DB) CreateSandbox(ctx context.Context, params database.CreateSandboxParams) error { return db.WithTx(ctx, func(ctx context.Context, op *database.Queries) error { if _, err := op.IncGlobalVersion(ctx); err != nil { diff --git a/packages/orchestrator/queries.sql b/packages/orchestrator/internal/db/queries.sql similarity index 61% rename from packages/orchestrator/queries.sql rename to packages/orchestrator/internal/db/queries.sql index d430a5aae..740b8c506 100644 --- a/packages/orchestrator/queries.sql +++ b/packages/orchestrator/internal/db/queries.sql @@ -5,7 +5,7 @@ SELECT version FROM status WHERE id = 1; UPDATE status SET version = version + 1, - updated_at = current_timestamp(), + updated_at = current_timestamp, status = 'running' WHERE id = 1 AND status = 'initializing'; @@ -14,7 +14,7 @@ WHERE UPDATE status SET version = version + 1, - updated_at = current_timestamp(), + updated_at = current_timestamp, status = 'terminated' WHERE id = 1 AND status != 'terminated'; @@ -23,7 +23,7 @@ WHERE UPDATE status SET version = version + 1, - updated_at = current_timestamp() + updated_at = current_timestamp WHERE id = 1 AND status != 'terminated' RETURNING version; @@ -44,7 +44,7 @@ UPDATE sandboxes SET version = version + 1, global_version = (SELECT version FROM status WHERE status.id = 1), - updated_at = current_timestamp(), + updated_at = current_timestamp, duration_ms = sqlc.arg('duration_ms'), status = sqlc.arg('status') WHERE @@ -55,8 +55,22 @@ UPDATE sandboxes SET version = version + 1, global_version = (SELECT version FROM status WHERE status.id = 1), - udpated_at = current_timestamp(), + udpated_at = current_timestamp, deadline = sqlc.arg('deadline'), status = 'running' WHERE sandboxes.id = sqlc.arg('id'); + +-- name: OrchestratorStatus :one +SELECT + status.version AS global_version, + (SELECT count(*) FROM sandboxes) AS num_sandboxes, + (SELECT count(*) FROM sandboxes WHERE status = 'pending') AS pending_sandboxes, + (SELECT count(*) FROM sandboxes WHERE status = 'terminated') AS terminated_sandboxes, + (SELECT count(*) FROM sandboxes WHERE status = 'running') AS running_sandboxes, + (SELECT min(started_at) FROM sandboxes WHERE status = 'running') AS earliest_running_sandbox_started_at, + (SELECT max(updated_at) FROM sandboxes WHERE status = 'running') AS most_recent_running_sandbox_updated_at, + status.updated_at, + status.status +FROM + status; diff --git a/packages/orchestrator/schema.sql b/packages/orchestrator/internal/db/schema.sql similarity index 77% rename from packages/orchestrator/schema.sql rename to packages/orchestrator/internal/db/schema.sql index b80149610..a6e386504 100644 --- a/packages/orchestrator/schema.sql +++ b/packages/orchestrator/internal/db/schema.sql @@ -8,11 +8,11 @@ CREATE TABLE sandboxes ( deadline TIMESTAMP NOT NULL, status TEXT CHECK( status IN ('pending', 'running', 'paused', 'terminated')) NOT NULL DEFAULT 'pending', - duration_ms INTEGER CHECK( duration_ms > 0 ) - NOT NULL, - version INTEGER CHECK( version > 0 ) - NOT NULL, - global_version INTEGER CHECK( global_version > 0 ) + duration_ms INTEGER CHECK( duration_ms >= 0 ) + NOT NULL DEFAULT 0, + version INTEGER CHECK( version >= 0 ) + NOT NULL DEFAULT 0, + global_version INTEGER CHECK( global_version >= 0 ) NOT NULL, config BLOB ); diff --git a/packages/orchestrator/internal/pkg/database/helpers.go b/packages/orchestrator/internal/pkg/database/helpers.go new file mode 100644 index 000000000..6f079ea04 --- /dev/null +++ b/packages/orchestrator/internal/pkg/database/helpers.go @@ -0,0 +1,44 @@ +package database + +import ( + "time" +) + +const sqliteDateTimeFormat = "2006-01-02 15:04:05.000000000+00:00" + +func (osr *OrchestratorStatusRow) OldestSandboxStartTime() (out time.Time) { + var err error + switch tt := osr.EarliestRunningSandboxStartedAt.(type) { + case string: + out, err = time.Parse(sqliteDateTimeFormat, tt) + if err != nil { + panic(err) + } + + case time.Time: + out = tt + case *time.Time: + out = *tt + } + out = out.UTC() + return +} + +func (osr *OrchestratorStatusRow) MostRecentSandboxModification() (out time.Time) { + var err error + switch tt := osr.MostRecentRunningSandboxUpdatedAt.(type) { + case string: + out, err = time.Parse(time.DateTime, tt) + if err != nil { + panic(err) + } + case time.Time: + out = tt + case *time.Time: + out = *tt + } + + out = out.UTC() + + return +} diff --git a/packages/orchestrator/internal/pkg/database/queries.sql.go b/packages/orchestrator/internal/pkg/database/queries.sql.go index e50a5bd12..0f94edc54 100644 --- a/packages/orchestrator/internal/pkg/database/queries.sql.go +++ b/packages/orchestrator/internal/pkg/database/queries.sql.go @@ -11,12 +11,13 @@ import ( ) const createSandbox = `-- name: CreateSandbox :exec -INSERT INTO sandboxes(id, status, started_at, deadline, config, global_version) +INSERT INTO sandboxes(id, status, started_at, deadline, duration_ms, config, global_version) VALUES ( ?1, ?2, ?3, ?4, + 0, ?5, (SELECT version FROM status WHERE status.id = 1) ) @@ -56,7 +57,7 @@ const incGlobalVersion = `-- name: IncGlobalVersion :one UPDATE status SET version = version + 1, - updated_at = current_timestamp() + updated_at = current_timestamp WHERE id = 1 AND status != 'terminated' RETURNING version @@ -69,11 +70,55 @@ func (q *Queries) IncGlobalVersion(ctx context.Context) (int64, error) { return version, err } +const orchestratorStatus = `-- name: OrchestratorStatus :one +SELECT + status.version AS global_version, + (SELECT count(*) FROM sandboxes) AS num_sandboxes, + (SELECT count(*) FROM sandboxes WHERE status = 'pending') AS pending_sandboxes, + (SELECT count(*) FROM sandboxes WHERE status = 'terminated') AS terminated_sandboxes, + (SELECT count(*) FROM sandboxes WHERE status = 'running') AS running_sandboxes, + (SELECT min(started_at) FROM sandboxes WHERE status = 'running') AS earliest_running_sandbox_started_at, + (SELECT max(updated_at) FROM sandboxes WHERE status = 'running') AS most_recent_running_sandbox_updated_at, + status.updated_at, + status.status +FROM + status +` + +type OrchestratorStatusRow struct { + GlobalVersion int64 + NumSandboxes int64 + PendingSandboxes int64 + TerminatedSandboxes int64 + RunningSandboxes int64 + EarliestRunningSandboxStartedAt interface{} + MostRecentRunningSandboxUpdatedAt interface{} + UpdatedAt time.Time + Status string +} + +func (q *Queries) OrchestratorStatus(ctx context.Context) (OrchestratorStatusRow, error) { + row := q.db.QueryRowContext(ctx, orchestratorStatus) + var i OrchestratorStatusRow + err := row.Scan( + &i.GlobalVersion, + &i.NumSandboxes, + &i.PendingSandboxes, + &i.TerminatedSandboxes, + &i.RunningSandboxes, + &i.EarliestRunningSandboxStartedAt, + &i.MostRecentRunningSandboxUpdatedAt, + &i.UpdatedAt, + &i.Status, + ) + return i, err +} + const setOrchestratorStatusRunning = `-- name: SetOrchestratorStatusRunning :exec UPDATE status SET version = version + 1, - updated_at = current_timestamp(), + updated_at = current_timestamp, status = 'running' WHERE id = 1 AND status = 'initializing' @@ -88,7 +133,7 @@ const setOrchestratorStatusTerminated = `-- name: SetOrchestratorStatusTerminate UPDATE status SET version = version + 1, - updated_at = current_timestamp(), + updated_at = current_timestamp, status = 'terminated' WHERE id = 1 AND status != 'terminated' @@ -104,7 +149,7 @@ UPDATE sandboxes SET version = version + 1, global_version = (SELECT version FROM status WHERE status.id = 1), - updated_at = current_timestamp(), + updated_at = current_timestamp, duration_ms = ?1, status = ?2 WHERE @@ -127,7 +172,7 @@ UPDATE sandboxes SET version = version + 1, global_version = (SELECT version FROM status WHERE status.id = 1), - udpated_at = current_timestamp(), + udpated_at = current_timestamp, deadline = ?1, status = 'running' WHERE diff --git a/packages/orchestrator/internal/server/main.go b/packages/orchestrator/internal/server/main.go index d713a0ad2..7d0353b3d 100644 --- a/packages/orchestrator/internal/server/main.go +++ b/packages/orchestrator/internal/server/main.go @@ -82,23 +82,34 @@ type Service struct { useClickhouseMetrics string } -func New(ctx context.Context, port uint, clientID string, version string, proxy *proxy.SandboxProxy) (*Service, error) { - if port > math.MaxUint16 { - return nil, fmt.Errorf("%d is larger than maximum possible port %d", port, math.MaxInt16) +type ServiceConf struct { + Version string + ClientID string + Schema string + Port uint +} + +func New( + ctx context.Context, + conf ServiceConf, + proxy *proxy.SandboxProxy, +) (*Service, error) { + if conf.Port > math.MaxUint16 { + return nil, fmt.Errorf("%d is larger than maximum possible port %d", conf.Port, math.MaxInt16) } - if clientID == "" { + if conf.ClientID == "" { return nil, errors.New("clientID is required") } - srv := &Service{version: version, port: uint16(port)} + srv := &Service{version: conf.Version, port: uint16(conf.Port)} templateCache, err := template.NewCache(ctx) if err != nil { return nil, fmt.Errorf("failed to create template cache: %w", err) } - networkPool, err := network.NewPool(ctx, network.NewSlotsPoolSize, network.ReusedSlotsPoolSize, clientID) + networkPool, err := network.NewPool(ctx, network.NewSlotsPoolSize, network.ReusedSlotsPoolSize, conf.ClientID) if err != nil { return nil, fmt.Errorf("failed to create network pool: %w", err) } @@ -161,7 +172,7 @@ func New(ctx context.Context, port uint, clientID string, version string, proxy sandboxes: smap.New[*sandbox.Sandbox](), networkPool: networkPool, templateCache: templateCache, - clientID: clientID, + clientID: conf.ClientID, devicePool: devicePool, clickhouseStore: clickhouseStore, useLokiMetrics: useLokiMetrics, @@ -178,15 +189,15 @@ func New(ctx context.Context, port uint, clientID string, version string, proxy } // BLOCK: setup database - const dbConnStr = "file:./db/sandboxes.db?_journal_mode=wal" - drv, err := sql.Open("sqlite3", dbConnStr) + const dbpath = "./db/sandboxes.db" + drv, err := newDatabaseDriver(dbpath) if err != nil { - return nil, fmt.Errorf("connecting to %q: %w", dbConnStr, err) + return nil, err } - srv.db, err = db.New(ctx, drv) + srv.db, err = db.New(ctx, drv, conf.Schema) if err != nil { - return nil, fmt.Errorf("using database at %q: %w", dbConnStr, err) + return nil, fmt.Errorf("using database at %q: %w", dbpath, err) } // BLOCK: register services and return @@ -198,6 +209,15 @@ func New(ctx context.Context, port uint, clientID string, version string, proxy return srv, nil } +func newDatabaseDriver(path string) (*sql.DB, error) { + connStr := fmt.Sprintf("file:%s?_journal_mode=wal", path) + drv, err := sql.Open("sqlite3", connStr) + if err != nil { + return nil, fmt.Errorf("connecting to %q: %w", connStr, err) + } + return drv, nil +} + // Start launches func (srv *Service) Start(ctx context.Context) error { if srv.server == nil || srv.dns == nil || srv.grpc == nil { @@ -300,8 +320,6 @@ func (srv *Service) Start(ctx context.Context) error { return nil } -func (srv *Service) SetupDB(ctx context.Context, ddl string) error { return srv.db.Init(ctx, ddl) } - func (srv *Service) Close(ctx context.Context) error { srv.shutdown.once.Do(func() { if srv.shutdown.op == nil { diff --git a/packages/orchestrator/internal/server/sandboxes.go b/packages/orchestrator/internal/server/sandboxes.go index 054a6f68a..c8fd23b0d 100644 --- a/packages/orchestrator/internal/server/sandboxes.go +++ b/packages/orchestrator/internal/server/sandboxes.go @@ -70,28 +70,22 @@ func (s *server) Create(ctxConn context.Context, req *orchestrator.SandboxCreate zap.L().Error("failed to create sandbox, cleaning up", zap.Error(err)) cleanupErr := cleanup.Run(ctx) - err = status.Errorf(codes.Internal, "failed to cleanup sandbox: %w", errors.Join(err, context.Cause(ctx), cleanupErr)) + err = status.Errorf(codes.Internal, "failed to create sandbox: %v", errors.Join(err, context.Cause(ctx), cleanupErr)) telemetry.ReportCriticalError(ctx, err) return nil, err } - started := time.Now() - // TODO: this could become JSON (pro: easier to read with external tools/code, con: larger size and slower serialization.) - confProto, err := proto.Marshal(sbx.Config) + started, err := s.recordSandboxStart(ctx, sbx) if err != nil { - sbxlogger.I(sbx).Error("failed to marshal sandbox config for the database", zap.Error(err)) - } + zap.L().Error("failed to register sandbox, cleaning up", zap.Error(err)) + + cleanupErr := cleanup.Run(ctx) + + err = status.Errorf(codes.Internal, "failed to register sandbox: %v", errors.Join(err, context.Cause(ctx), cleanupErr)) + telemetry.ReportCriticalError(ctx, err) - s.sandboxes.Insert(req.Sandbox.SandboxId, sbx) - if err := s.db.CreateSandbox(ctx, database.CreateSandboxParams{ - ID: req.Sandbox.SandboxId, - Status: database.SandboxStatusRunning, - StartedAt: started, - Deadline: req.EndTime.AsTime(), - Config: confProto, - }); err != nil { return nil, err } @@ -136,6 +130,32 @@ func (s *server) Create(ctxConn context.Context, req *orchestrator.SandboxCreate }, nil } +func (s *server) recordSandboxStart(ctx context.Context, sbx *sandbox.Sandbox) (time.Time, error) { + started := time.Now().UTC() + s.sandboxes.Insert(sbx.Config.SandboxId, sbx) + + // TODO: this could become JSON (pro: easier to read with + // external tools/code, con: larger size and slower + // serialization.) + confProto, err := proto.Marshal(sbx.Config) + if err != nil { + // TODO: decide if we want to return early and abort in this case. + sbxlogger.I(sbx).Error("failed to marshal sandbox config for the database", zap.Error(err)) + } + + if err := s.db.CreateSandbox(ctx, database.CreateSandboxParams{ + ID: sbx.Config.SandboxId, + Status: database.SandboxStatusRunning, + StartedAt: started, + Deadline: sbx.EndAt, + Config: confProto, + }); err != nil { + return started, err + } + + return started, nil +} + func (s *server) Update(ctx context.Context, req *orchestrator.SandboxUpdateRequest) (*emptypb.Empty, error) { ctx, childSpan := s.tracer.Start(ctx, "sandbox-update") defer childSpan.End() @@ -154,7 +174,7 @@ func (s *server) Update(ctx context.Context, req *orchestrator.SandboxUpdateRequ item.EndAt = req.EndTime.AsTime() if err := s.db.UpdateSandboxDeadline(ctx, req.SandboxId, item.EndAt); err != nil { - return nil, status.Errorf(codes.Internal, fmt.Sprintf("db update sandbox: %w", err)) + return nil, status.Errorf(codes.Internal, "db update sandbox: %v", err) } return &emptypb.Empty{}, nil @@ -396,3 +416,22 @@ func (s *server) Pause(ctx context.Context, in *orchestrator.SandboxPauseRequest return &emptypb.Empty{}, nil } + +func (s *server) StatusReport(ctx context.Context, _ *emptypb.Empty) (*orchestrator.OrchestratorStatus, error) { + report, err := s.db.Status(ctx) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &orchestrator.OrchestratorStatus{ + GlobalVersion: report.GlobalVersion, + RunningSandboxes: report.RunningSandboxes, + PendingSandboxes: report.PendingSandboxes, + TerminatedSandboxes: report.TerminatedSandboxes, + NumSandboxes: report.NumSandboxes, + Status: report.Status, + UpdatedAt: timestamppb.New(report.UpdatedAt), + EarliestRunningSandboxStartedAt: timestamppb.New(report.OldestSandboxStartTime()), + MostRecentRunningSandboxUpdatedAt: timestamppb.New(report.MostRecentSandboxModification()), + }, nil +} diff --git a/packages/orchestrator/internal/server/sandboxes_test.go b/packages/orchestrator/internal/server/sandboxes_test.go index d7e72c136..0575c4e56 100644 --- a/packages/orchestrator/internal/server/sandboxes_test.go +++ b/packages/orchestrator/internal/server/sandboxes_test.go @@ -2,21 +2,28 @@ package server import ( "context" + "fmt" + "os" + "path/filepath" "reflect" "testing" "time" + "github.com/e2b-dev/infra/packages/orchestrator/internal/db" "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox" "github.com/e2b-dev/infra/packages/shared/pkg/grpc/orchestrator" "github.com/e2b-dev/infra/packages/shared/pkg/smap" + "github.com/google/uuid" + _ "github.com/mattn/go-sqlite3" + "github.com/stretchr/testify/assert" "go.opentelemetry.io/otel/trace/noop" "google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/timestamppb" ) var ( - startTime = time.Now() - endTime = time.Now().Add(time.Hour) + startTime = time.Now().UTC() + endTime = startTime.Add(time.Hour) ) func Test_server_List(t *testing.T) { @@ -80,3 +87,76 @@ func Test_server_List(t *testing.T) { }) } } + +func TestDatabaseSmokeTest(t *testing.T) { + ctx := t.Context() + + schemaPath, err := filepath.Abs("../db/schema.sql") + if err != nil { + t.Fatal(err) + } + + schema, err := os.ReadFile(schemaPath) + if err != nil { + t.Fatal(err) + } + + path := filepath.Join(t.TempDir(), fmt.Sprintf("%s.%d.%d.db", t.Name(), time.Now().UTC().Unix(), os.Getpid())) + drv, err := newDatabaseDriver(path) + if err != nil { + t.Fatal(err) + } + + srvDB, err := db.New(ctx, drv, string(schema)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + + if err := srvDB.Close(ctx); err != nil { + t.Fatal(err) + } + }) + + status, err := srvDB.Status(ctx) + if err != nil { + t.Fatal(err) + } + + assert.Equal(t, int64(1), status.GlobalVersion) + assert.Equal(t, int64(0), status.NumSandboxes) + assert.Equal(t, int64(0), status.RunningSandboxes) + + srv := &server{ + sandboxes: smap.New[*sandbox.Sandbox](), + db: srvDB, + } + + id := uuid.New() + sbxOriginal := &sandbox.Sandbox{ + Config: &orchestrator.SandboxConfig{SandboxId: id.String()}, + EndAt: time.Now().UTC().Add(time.Hour), + } + + started, err := srv.recordSandboxStart(ctx, sbxOriginal) + if err != nil { + t.Fatal(err) + } + + assert.True(t, started.Before(sbxOriginal.EndAt)) + + status, err = srvDB.Status(ctx) + if err != nil { + t.Fatal(err) + } + + assert.Equal(t, int64(2), status.GlobalVersion) + assert.Equal(t, int64(1), status.NumSandboxes) + assert.Equal(t, int64(1), status.RunningSandboxes) + assert.Equal(t, + started.Truncate(time.Millisecond), + status.OldestSandboxStartTime().Truncate(time.Millisecond), + ) +} diff --git a/packages/orchestrator/main.go b/packages/orchestrator/main.go index 7c0325c8f..1fc586a24 100644 --- a/packages/orchestrator/main.go +++ b/packages/orchestrator/main.go @@ -2,6 +2,7 @@ package main import ( "context" + _ "embed" "errors" "flag" "fmt" @@ -22,6 +23,7 @@ import ( "github.com/e2b-dev/infra/packages/shared/pkg/logger" sbxlogger "github.com/e2b-dev/infra/packages/shared/pkg/logger/sandbox" "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" + _ "github.com/mattn/go-sqlite3" ) const ( @@ -32,8 +34,8 @@ const ( var commitSHA string -//go:embed schema.sql -var ddl string +//go:embed internal/db/schema.sql +var schema string func run() int { ctx, cancel := context.WithCancel(context.Background()) @@ -107,15 +109,18 @@ func run() int { sessionProxy := proxy.New(proxyPort) - srv, err := server.New(ctx, port, clientID, commitSHA, sessionProxy) + srv, err := server.New(ctx, + server.ServiceConf{ + Version: commitSHA, + Port: port, + ClientID: clientID, + Schema: schema, + }, + sessionProxy) if err != nil { zap.L().Panic("failed to create server", zap.Error(err)) } - if err := srv.SetupDB(ctx, ddl); err != nil { - zap.L().Panic("failed database setup", zap.Error(err)) - } - wg.Add(1) go func() { defer wg.Done() diff --git a/packages/orchestrator/orchestrator.proto b/packages/orchestrator/orchestrator.proto index b84dacfa6..3e7dcc165 100644 --- a/packages/orchestrator/orchestrator.proto +++ b/packages/orchestrator/orchestrator.proto @@ -9,20 +9,20 @@ message SandboxConfig { // Data required for creating a new sandbox. string template_id = 1; string build_id = 2; - + string kernel_version = 3; string firecracker_version = 4; - + bool huge_pages = 5; - + string sandbox_id = 6; map env_vars = 7; - + // Metadata about the sandbox. map metadata = 8; optional string alias = 9; string envd_version = 10; - + int64 vcpu = 11; int64 ram_mb = 12; @@ -86,7 +86,17 @@ message SandboxListCachedBuildsResponse { repeated CachedBuildInfo builds = 1; } - +message OrchestratorStatus { + int64 global_version = 1; + int64 running_sandboxes = 2; + int64 pending_sandboxes = 4; + int64 terminated_sandboxes = 5; + int64 num_sandboxes = 6; + string status = 7; + google.protobuf.Timestamp updated_at = 8; + google.protobuf.Timestamp earliest_running_sandbox_started_at = 9; + google.protobuf.Timestamp most_recent_running_sandbox_updated_at = 10; +} service SandboxService { rpc Create(SandboxCreateRequest) returns (SandboxCreateResponse); @@ -96,4 +106,5 @@ service SandboxService { rpc Pause(SandboxPauseRequest) returns (google.protobuf.Empty); rpc ListCachedBuilds(google.protobuf.Empty) returns (SandboxListCachedBuildsResponse); + rpc StatusReport(google.protobuf.Empty) returns (OrchestratorStatus); } diff --git a/packages/shared/pkg/grpc/orchestrator/orchestrator.pb.go b/packages/shared/pkg/grpc/orchestrator/orchestrator.pb.go index 6ec1f395c..1bbdba9ed 100644 --- a/packages/shared/pkg/grpc/orchestrator/orchestrator.pb.go +++ b/packages/shared/pkg/grpc/orchestrator/orchestrator.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v5.29.3 +// protoc-gen-go v1.36.6 +// protoc v5.29.2 // source: orchestrator.proto package orchestrator @@ -13,6 +13,7 @@ import ( timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -23,10 +24,7 @@ const ( ) type SandboxConfig struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Data required for creating a new sandbox. TemplateId string `protobuf:"bytes,1,opt,name=template_id,json=templateId,proto3" json:"template_id,omitempty"` BuildId string `protobuf:"bytes,2,opt,name=build_id,json=buildId,proto3" json:"build_id,omitempty"` @@ -34,9 +32,9 @@ type SandboxConfig struct { FirecrackerVersion string `protobuf:"bytes,4,opt,name=firecracker_version,json=firecrackerVersion,proto3" json:"firecracker_version,omitempty"` HugePages bool `protobuf:"varint,5,opt,name=huge_pages,json=hugePages,proto3" json:"huge_pages,omitempty"` SandboxId string `protobuf:"bytes,6,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` - EnvVars map[string]string `protobuf:"bytes,7,rep,name=env_vars,json=envVars,proto3" json:"env_vars,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + EnvVars map[string]string `protobuf:"bytes,7,rep,name=env_vars,json=envVars,proto3" json:"env_vars,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // Metadata about the sandbox. - Metadata map[string]string `protobuf:"bytes,8,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + Metadata map[string]string `protobuf:"bytes,8,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Alias *string `protobuf:"bytes,9,opt,name=alias,proto3,oneof" json:"alias,omitempty"` EnvdVersion string `protobuf:"bytes,10,opt,name=envd_version,json=envdVersion,proto3" json:"envd_version,omitempty"` Vcpu int64 `protobuf:"varint,11,opt,name=vcpu,proto3" json:"vcpu,omitempty"` @@ -48,15 +46,15 @@ type SandboxConfig struct { Snapshot bool `protobuf:"varint,16,opt,name=snapshot,proto3" json:"snapshot,omitempty"` BaseTemplateId string `protobuf:"bytes,17,opt,name=base_template_id,json=baseTemplateId,proto3" json:"base_template_id,omitempty"` AutoPause *bool `protobuf:"varint,18,opt,name=auto_pause,json=autoPause,proto3,oneof" json:"auto_pause,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *SandboxConfig) Reset() { *x = SandboxConfig{} - if protoimpl.UnsafeEnabled { - mi := &file_orchestrator_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_orchestrator_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SandboxConfig) String() string { @@ -67,7 +65,7 @@ func (*SandboxConfig) ProtoMessage() {} func (x *SandboxConfig) ProtoReflect() protoreflect.Message { mi := &file_orchestrator_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -209,22 +207,19 @@ func (x *SandboxConfig) GetAutoPause() bool { } type SandboxCreateRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + Sandbox *SandboxConfig `protobuf:"bytes,1,opt,name=sandbox,proto3" json:"sandbox,omitempty"` + StartTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"` + EndTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` unknownFields protoimpl.UnknownFields - - Sandbox *SandboxConfig `protobuf:"bytes,1,opt,name=sandbox,proto3" json:"sandbox,omitempty"` - StartTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"` - EndTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` + sizeCache protoimpl.SizeCache } func (x *SandboxCreateRequest) Reset() { *x = SandboxCreateRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_orchestrator_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_orchestrator_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SandboxCreateRequest) String() string { @@ -235,7 +230,7 @@ func (*SandboxCreateRequest) ProtoMessage() {} func (x *SandboxCreateRequest) ProtoReflect() protoreflect.Message { mi := &file_orchestrator_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -272,20 +267,17 @@ func (x *SandboxCreateRequest) GetEndTime() *timestamppb.Timestamp { } type SandboxCreateResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + ClientId string `protobuf:"bytes,1,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"` unknownFields protoimpl.UnknownFields - - ClientId string `protobuf:"bytes,1,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"` + sizeCache protoimpl.SizeCache } func (x *SandboxCreateResponse) Reset() { *x = SandboxCreateResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_orchestrator_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_orchestrator_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SandboxCreateResponse) String() string { @@ -296,7 +288,7 @@ func (*SandboxCreateResponse) ProtoMessage() {} func (x *SandboxCreateResponse) ProtoReflect() protoreflect.Message { mi := &file_orchestrator_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -319,21 +311,18 @@ func (x *SandboxCreateResponse) GetClientId() string { } type SandboxUpdateRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` + EndTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` unknownFields protoimpl.UnknownFields - - SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` - EndTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` + sizeCache protoimpl.SizeCache } func (x *SandboxUpdateRequest) Reset() { *x = SandboxUpdateRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_orchestrator_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_orchestrator_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SandboxUpdateRequest) String() string { @@ -344,7 +333,7 @@ func (*SandboxUpdateRequest) ProtoMessage() {} func (x *SandboxUpdateRequest) ProtoReflect() protoreflect.Message { mi := &file_orchestrator_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -374,20 +363,17 @@ func (x *SandboxUpdateRequest) GetEndTime() *timestamppb.Timestamp { } type SandboxDeleteRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` unknownFields protoimpl.UnknownFields - - SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` + sizeCache protoimpl.SizeCache } func (x *SandboxDeleteRequest) Reset() { *x = SandboxDeleteRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_orchestrator_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_orchestrator_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SandboxDeleteRequest) String() string { @@ -398,7 +384,7 @@ func (*SandboxDeleteRequest) ProtoMessage() {} func (x *SandboxDeleteRequest) ProtoReflect() protoreflect.Message { mi := &file_orchestrator_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -421,22 +407,19 @@ func (x *SandboxDeleteRequest) GetSandboxId() string { } type SandboxPauseRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` + TemplateId string `protobuf:"bytes,2,opt,name=template_id,json=templateId,proto3" json:"template_id,omitempty"` + BuildId string `protobuf:"bytes,3,opt,name=build_id,json=buildId,proto3" json:"build_id,omitempty"` unknownFields protoimpl.UnknownFields - - SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` - TemplateId string `protobuf:"bytes,2,opt,name=template_id,json=templateId,proto3" json:"template_id,omitempty"` - BuildId string `protobuf:"bytes,3,opt,name=build_id,json=buildId,proto3" json:"build_id,omitempty"` + sizeCache protoimpl.SizeCache } func (x *SandboxPauseRequest) Reset() { *x = SandboxPauseRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_orchestrator_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_orchestrator_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SandboxPauseRequest) String() string { @@ -447,7 +430,7 @@ func (*SandboxPauseRequest) ProtoMessage() {} func (x *SandboxPauseRequest) ProtoReflect() protoreflect.Message { mi := &file_orchestrator_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -484,23 +467,20 @@ func (x *SandboxPauseRequest) GetBuildId() string { } type RunningSandbox struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + Config *SandboxConfig `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` + ClientId string `protobuf:"bytes,2,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"` + StartTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"` + EndTime *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` unknownFields protoimpl.UnknownFields - - Config *SandboxConfig `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` - ClientId string `protobuf:"bytes,2,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"` - StartTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"` - EndTime *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` + sizeCache protoimpl.SizeCache } func (x *RunningSandbox) Reset() { *x = RunningSandbox{} - if protoimpl.UnsafeEnabled { - mi := &file_orchestrator_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_orchestrator_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *RunningSandbox) String() string { @@ -511,7 +491,7 @@ func (*RunningSandbox) ProtoMessage() {} func (x *RunningSandbox) ProtoReflect() protoreflect.Message { mi := &file_orchestrator_proto_msgTypes[6] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -555,20 +535,17 @@ func (x *RunningSandbox) GetEndTime() *timestamppb.Timestamp { } type SandboxListResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + Sandboxes []*RunningSandbox `protobuf:"bytes,1,rep,name=sandboxes,proto3" json:"sandboxes,omitempty"` unknownFields protoimpl.UnknownFields - - Sandboxes []*RunningSandbox `protobuf:"bytes,1,rep,name=sandboxes,proto3" json:"sandboxes,omitempty"` + sizeCache protoimpl.SizeCache } func (x *SandboxListResponse) Reset() { *x = SandboxListResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_orchestrator_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_orchestrator_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SandboxListResponse) String() string { @@ -579,7 +556,7 @@ func (*SandboxListResponse) ProtoMessage() {} func (x *SandboxListResponse) ProtoReflect() protoreflect.Message { mi := &file_orchestrator_proto_msgTypes[7] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -602,21 +579,18 @@ func (x *SandboxListResponse) GetSandboxes() []*RunningSandbox { } type CachedBuildInfo struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` BuildId string `protobuf:"bytes,1,opt,name=build_id,json=buildId,proto3" json:"build_id,omitempty"` ExpirationTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=expiration_time,json=expirationTime,proto3" json:"expiration_time,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CachedBuildInfo) Reset() { *x = CachedBuildInfo{} - if protoimpl.UnsafeEnabled { - mi := &file_orchestrator_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_orchestrator_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *CachedBuildInfo) String() string { @@ -627,7 +601,7 @@ func (*CachedBuildInfo) ProtoMessage() {} func (x *CachedBuildInfo) ProtoReflect() protoreflect.Message { mi := &file_orchestrator_proto_msgTypes[8] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -657,20 +631,17 @@ func (x *CachedBuildInfo) GetExpirationTime() *timestamppb.Timestamp { } type SandboxListCachedBuildsResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + Builds []*CachedBuildInfo `protobuf:"bytes,1,rep,name=builds,proto3" json:"builds,omitempty"` unknownFields protoimpl.UnknownFields - - Builds []*CachedBuildInfo `protobuf:"bytes,1,rep,name=builds,proto3" json:"builds,omitempty"` + sizeCache protoimpl.SizeCache } func (x *SandboxListCachedBuildsResponse) Reset() { *x = SandboxListCachedBuildsResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_orchestrator_proto_msgTypes[9] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_orchestrator_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *SandboxListCachedBuildsResponse) String() string { @@ -681,7 +652,7 @@ func (*SandboxListCachedBuildsResponse) ProtoMessage() {} func (x *SandboxListCachedBuildsResponse) ProtoReflect() protoreflect.Message { mi := &file_orchestrator_proto_msgTypes[9] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -703,170 +674,219 @@ func (x *SandboxListCachedBuildsResponse) GetBuilds() []*CachedBuildInfo { return nil } -var File_orchestrator_proto protoreflect.FileDescriptor +type OrchestratorStatus struct { + state protoimpl.MessageState `protogen:"open.v1"` + GlobalVersion int64 `protobuf:"varint,1,opt,name=global_version,json=globalVersion,proto3" json:"global_version,omitempty"` + RunningSandboxes int64 `protobuf:"varint,2,opt,name=running_sandboxes,json=runningSandboxes,proto3" json:"running_sandboxes,omitempty"` + PendingSandboxes int64 `protobuf:"varint,4,opt,name=pending_sandboxes,json=pendingSandboxes,proto3" json:"pending_sandboxes,omitempty"` + TerminatedSandboxes int64 `protobuf:"varint,5,opt,name=terminated_sandboxes,json=terminatedSandboxes,proto3" json:"terminated_sandboxes,omitempty"` + NumSandboxes int64 `protobuf:"varint,6,opt,name=num_sandboxes,json=numSandboxes,proto3" json:"num_sandboxes,omitempty"` + Status string `protobuf:"bytes,7,opt,name=status,proto3" json:"status,omitempty"` + UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,8,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` + EarliestRunningSandboxStartedAt *timestamppb.Timestamp `protobuf:"bytes,9,opt,name=earliest_running_sandbox_started_at,json=earliestRunningSandboxStartedAt,proto3" json:"earliest_running_sandbox_started_at,omitempty"` + MostRecentRunningSandboxUpdatedAt *timestamppb.Timestamp `protobuf:"bytes,10,opt,name=most_recent_running_sandbox_updated_at,json=mostRecentRunningSandboxUpdatedAt,proto3" json:"most_recent_running_sandbox_updated_at,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} -var file_orchestrator_proto_rawDesc = []byte{ - 0x0a, 0x12, 0x6f, 0x72, 0x63, 0x68, 0x65, 0x73, 0x74, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x22, 0xac, 0x06, 0x0a, 0x0d, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x43, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x12, 0x1f, 0x0a, 0x0b, 0x74, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, - 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, 0x65, 0x6d, 0x70, 0x6c, - 0x61, 0x74, 0x65, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x5f, 0x69, - 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x49, 0x64, - 0x12, 0x25, 0x0a, 0x0e, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, - 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, - 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2f, 0x0a, 0x13, 0x66, 0x69, 0x72, 0x65, 0x63, - 0x72, 0x61, 0x63, 0x6b, 0x65, 0x72, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x12, 0x66, 0x69, 0x72, 0x65, 0x63, 0x72, 0x61, 0x63, 0x6b, 0x65, - 0x72, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1d, 0x0a, 0x0a, 0x68, 0x75, 0x67, 0x65, - 0x5f, 0x70, 0x61, 0x67, 0x65, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x09, 0x68, 0x75, - 0x67, 0x65, 0x50, 0x61, 0x67, 0x65, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x61, 0x6e, 0x64, 0x62, - 0x6f, 0x78, 0x5f, 0x69, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x61, 0x6e, - 0x64, 0x62, 0x6f, 0x78, 0x49, 0x64, 0x12, 0x36, 0x0a, 0x08, 0x65, 0x6e, 0x76, 0x5f, 0x76, 0x61, - 0x72, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x53, 0x61, 0x6e, 0x64, 0x62, - 0x6f, 0x78, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x45, 0x6e, 0x76, 0x56, 0x61, 0x72, 0x73, - 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x07, 0x65, 0x6e, 0x76, 0x56, 0x61, 0x72, 0x73, 0x12, 0x38, - 0x0a, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x1c, 0x2e, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x2e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x08, - 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x19, 0x0a, 0x05, 0x61, 0x6c, 0x69, 0x61, - 0x73, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x05, 0x61, 0x6c, 0x69, 0x61, 0x73, - 0x88, 0x01, 0x01, 0x12, 0x21, 0x0a, 0x0c, 0x65, 0x6e, 0x76, 0x64, 0x5f, 0x76, 0x65, 0x72, 0x73, - 0x69, 0x6f, 0x6e, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x65, 0x6e, 0x76, 0x64, 0x56, - 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x76, 0x63, 0x70, 0x75, 0x18, 0x0b, - 0x20, 0x01, 0x28, 0x03, 0x52, 0x04, 0x76, 0x63, 0x70, 0x75, 0x12, 0x15, 0x0a, 0x06, 0x72, 0x61, - 0x6d, 0x5f, 0x6d, 0x62, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x72, 0x61, 0x6d, 0x4d, - 0x62, 0x12, 0x17, 0x0a, 0x07, 0x74, 0x65, 0x61, 0x6d, 0x5f, 0x69, 0x64, 0x18, 0x0d, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x06, 0x74, 0x65, 0x61, 0x6d, 0x49, 0x64, 0x12, 0x2c, 0x0a, 0x12, 0x6d, 0x61, - 0x78, 0x5f, 0x73, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x5f, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, - 0x18, 0x0e, 0x20, 0x01, 0x28, 0x03, 0x52, 0x10, 0x6d, 0x61, 0x78, 0x53, 0x61, 0x6e, 0x64, 0x62, - 0x6f, 0x78, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x12, 0x2b, 0x0a, 0x12, 0x74, 0x6f, 0x74, 0x61, - 0x6c, 0x5f, 0x64, 0x69, 0x73, 0x6b, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x5f, 0x6d, 0x62, 0x18, 0x0f, - 0x20, 0x01, 0x28, 0x03, 0x52, 0x0f, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x44, 0x69, 0x73, 0x6b, 0x53, - 0x69, 0x7a, 0x65, 0x4d, 0x62, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x6e, 0x61, 0x70, 0x73, 0x68, 0x6f, - 0x74, 0x18, 0x10, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x73, 0x6e, 0x61, 0x70, 0x73, 0x68, 0x6f, - 0x74, 0x12, 0x28, 0x0a, 0x10, 0x62, 0x61, 0x73, 0x65, 0x5f, 0x74, 0x65, 0x6d, 0x70, 0x6c, 0x61, - 0x74, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x11, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x62, 0x61, 0x73, - 0x65, 0x54, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x49, 0x64, 0x12, 0x22, 0x0a, 0x0a, 0x61, - 0x75, 0x74, 0x6f, 0x5f, 0x70, 0x61, 0x75, 0x73, 0x65, 0x18, 0x12, 0x20, 0x01, 0x28, 0x08, 0x48, - 0x01, 0x52, 0x09, 0x61, 0x75, 0x74, 0x6f, 0x50, 0x61, 0x75, 0x73, 0x65, 0x88, 0x01, 0x01, 0x1a, - 0x3a, 0x0a, 0x0c, 0x45, 0x6e, 0x76, 0x56, 0x61, 0x72, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, - 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, - 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x3b, 0x0a, 0x0d, 0x4d, - 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, - 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, - 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, - 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x61, 0x6c, 0x69, - 0x61, 0x73, 0x42, 0x0d, 0x0a, 0x0b, 0x5f, 0x61, 0x75, 0x74, 0x6f, 0x5f, 0x70, 0x61, 0x75, 0x73, - 0x65, 0x22, 0xb2, 0x01, 0x0a, 0x14, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x43, 0x72, 0x65, - 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x28, 0x0a, 0x07, 0x73, 0x61, - 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x53, 0x61, - 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x07, 0x73, 0x61, 0x6e, - 0x64, 0x62, 0x6f, 0x78, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, - 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, - 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, - 0x35, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x07, 0x65, - 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x22, 0x34, 0x0a, 0x15, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, - 0x78, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x1b, 0x0a, 0x09, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x08, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x22, 0x6c, 0x0a, 0x14, - 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x5f, - 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x61, 0x6e, 0x64, 0x62, 0x6f, - 0x78, 0x49, 0x64, 0x12, 0x35, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, - 0x70, 0x52, 0x07, 0x65, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x22, 0x35, 0x0a, 0x14, 0x53, 0x61, - 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x5f, 0x69, 0x64, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x49, - 0x64, 0x22, 0x70, 0x0a, 0x13, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x50, 0x61, 0x75, 0x73, - 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x61, 0x6e, 0x64, - 0x62, 0x6f, 0x78, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x61, - 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x74, 0x65, 0x6d, 0x70, 0x6c, - 0x61, 0x74, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, 0x65, - 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x75, 0x69, 0x6c, - 0x64, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x62, 0x75, 0x69, 0x6c, - 0x64, 0x49, 0x64, 0x22, 0xc7, 0x01, 0x0a, 0x0e, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x53, - 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x12, 0x26, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, - 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x1b, - 0x0a, 0x09, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x08, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x39, 0x0a, 0x0a, 0x73, - 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61, - 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, - 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, - 0x74, 0x61, 0x6d, 0x70, 0x52, 0x07, 0x65, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x22, 0x44, 0x0a, - 0x13, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2d, 0x0a, 0x09, 0x73, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x65, - 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, - 0x67, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x52, 0x09, 0x73, 0x61, 0x6e, 0x64, 0x62, 0x6f, - 0x78, 0x65, 0x73, 0x22, 0x71, 0x0a, 0x0f, 0x43, 0x61, 0x63, 0x68, 0x65, 0x64, 0x42, 0x75, 0x69, - 0x6c, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x5f, - 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x49, - 0x64, 0x12, 0x43, 0x0a, 0x0f, 0x65, 0x78, 0x70, 0x69, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, - 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, - 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0e, 0x65, 0x78, 0x70, 0x69, 0x72, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x22, 0x4b, 0x0a, 0x1f, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, - 0x78, 0x4c, 0x69, 0x73, 0x74, 0x43, 0x61, 0x63, 0x68, 0x65, 0x64, 0x42, 0x75, 0x69, 0x6c, 0x64, - 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x28, 0x0a, 0x06, 0x62, 0x75, 0x69, - 0x6c, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x43, 0x61, 0x63, 0x68, - 0x65, 0x64, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x06, 0x62, 0x75, 0x69, - 0x6c, 0x64, 0x73, 0x32, 0xf6, 0x02, 0x0a, 0x0e, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x53, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x37, 0x0a, 0x06, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, - 0x12, 0x15, 0x2e, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, - 0x78, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x37, 0x0a, 0x06, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x12, 0x15, 0x2e, 0x53, 0x61, 0x6e, 0x64, - 0x62, 0x6f, 0x78, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x34, 0x0a, 0x04, 0x4c, 0x69, 0x73, 0x74, - 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x14, 0x2e, 0x53, 0x61, 0x6e, 0x64, 0x62, - 0x6f, 0x78, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, - 0x0a, 0x06, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x12, 0x15, 0x2e, 0x53, 0x61, 0x6e, 0x64, 0x62, - 0x6f, 0x78, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, - 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x35, 0x0a, 0x05, 0x50, 0x61, 0x75, 0x73, 0x65, - 0x12, 0x14, 0x2e, 0x53, 0x61, 0x6e, 0x64, 0x62, 0x6f, 0x78, 0x50, 0x61, 0x75, 0x73, 0x65, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x4c, - 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x43, 0x61, 0x63, 0x68, 0x65, 0x64, 0x42, 0x75, 0x69, 0x6c, - 0x64, 0x73, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x20, 0x2e, 0x53, 0x61, 0x6e, - 0x64, 0x62, 0x6f, 0x78, 0x4c, 0x69, 0x73, 0x74, 0x43, 0x61, 0x63, 0x68, 0x65, 0x64, 0x42, 0x75, - 0x69, 0x6c, 0x64, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x2f, 0x5a, 0x2d, - 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, - 0x6f, 0x6d, 0x2f, 0x65, 0x32, 0x62, 0x2d, 0x64, 0x65, 0x76, 0x2f, 0x69, 0x6e, 0x66, 0x72, 0x61, - 0x2f, 0x6f, 0x72, 0x63, 0x68, 0x65, 0x73, 0x74, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x62, 0x06, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x33, +func (x *OrchestratorStatus) Reset() { + *x = OrchestratorStatus{} + mi := &file_orchestrator_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } +func (x *OrchestratorStatus) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OrchestratorStatus) ProtoMessage() {} + +func (x *OrchestratorStatus) ProtoReflect() protoreflect.Message { + mi := &file_orchestrator_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OrchestratorStatus.ProtoReflect.Descriptor instead. +func (*OrchestratorStatus) Descriptor() ([]byte, []int) { + return file_orchestrator_proto_rawDescGZIP(), []int{10} +} + +func (x *OrchestratorStatus) GetGlobalVersion() int64 { + if x != nil { + return x.GlobalVersion + } + return 0 +} + +func (x *OrchestratorStatus) GetRunningSandboxes() int64 { + if x != nil { + return x.RunningSandboxes + } + return 0 +} + +func (x *OrchestratorStatus) GetPendingSandboxes() int64 { + if x != nil { + return x.PendingSandboxes + } + return 0 +} + +func (x *OrchestratorStatus) GetTerminatedSandboxes() int64 { + if x != nil { + return x.TerminatedSandboxes + } + return 0 +} + +func (x *OrchestratorStatus) GetNumSandboxes() int64 { + if x != nil { + return x.NumSandboxes + } + return 0 +} + +func (x *OrchestratorStatus) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *OrchestratorStatus) GetUpdatedAt() *timestamppb.Timestamp { + if x != nil { + return x.UpdatedAt + } + return nil +} + +func (x *OrchestratorStatus) GetEarliestRunningSandboxStartedAt() *timestamppb.Timestamp { + if x != nil { + return x.EarliestRunningSandboxStartedAt + } + return nil +} + +func (x *OrchestratorStatus) GetMostRecentRunningSandboxUpdatedAt() *timestamppb.Timestamp { + if x != nil { + return x.MostRecentRunningSandboxUpdatedAt + } + return nil +} + +var File_orchestrator_proto protoreflect.FileDescriptor + +const file_orchestrator_proto_rawDesc = "" + + "\n" + + "\x12orchestrator.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\xac\x06\n" + + "\rSandboxConfig\x12\x1f\n" + + "\vtemplate_id\x18\x01 \x01(\tR\n" + + "templateId\x12\x19\n" + + "\bbuild_id\x18\x02 \x01(\tR\abuildId\x12%\n" + + "\x0ekernel_version\x18\x03 \x01(\tR\rkernelVersion\x12/\n" + + "\x13firecracker_version\x18\x04 \x01(\tR\x12firecrackerVersion\x12\x1d\n" + + "\n" + + "huge_pages\x18\x05 \x01(\bR\thugePages\x12\x1d\n" + + "\n" + + "sandbox_id\x18\x06 \x01(\tR\tsandboxId\x126\n" + + "\benv_vars\x18\a \x03(\v2\x1b.SandboxConfig.EnvVarsEntryR\aenvVars\x128\n" + + "\bmetadata\x18\b \x03(\v2\x1c.SandboxConfig.MetadataEntryR\bmetadata\x12\x19\n" + + "\x05alias\x18\t \x01(\tH\x00R\x05alias\x88\x01\x01\x12!\n" + + "\fenvd_version\x18\n" + + " \x01(\tR\venvdVersion\x12\x12\n" + + "\x04vcpu\x18\v \x01(\x03R\x04vcpu\x12\x15\n" + + "\x06ram_mb\x18\f \x01(\x03R\x05ramMb\x12\x17\n" + + "\ateam_id\x18\r \x01(\tR\x06teamId\x12,\n" + + "\x12max_sandbox_length\x18\x0e \x01(\x03R\x10maxSandboxLength\x12+\n" + + "\x12total_disk_size_mb\x18\x0f \x01(\x03R\x0ftotalDiskSizeMb\x12\x1a\n" + + "\bsnapshot\x18\x10 \x01(\bR\bsnapshot\x12(\n" + + "\x10base_template_id\x18\x11 \x01(\tR\x0ebaseTemplateId\x12\"\n" + + "\n" + + "auto_pause\x18\x12 \x01(\bH\x01R\tautoPause\x88\x01\x01\x1a:\n" + + "\fEnvVarsEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1a;\n" + + "\rMetadataEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01B\b\n" + + "\x06_aliasB\r\n" + + "\v_auto_pause\"\xb2\x01\n" + + "\x14SandboxCreateRequest\x12(\n" + + "\asandbox\x18\x01 \x01(\v2\x0e.SandboxConfigR\asandbox\x129\n" + + "\n" + + "start_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\tstartTime\x125\n" + + "\bend_time\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\aendTime\"4\n" + + "\x15SandboxCreateResponse\x12\x1b\n" + + "\tclient_id\x18\x01 \x01(\tR\bclientId\"l\n" + + "\x14SandboxUpdateRequest\x12\x1d\n" + + "\n" + + "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x125\n" + + "\bend_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\aendTime\"5\n" + + "\x14SandboxDeleteRequest\x12\x1d\n" + + "\n" + + "sandbox_id\x18\x01 \x01(\tR\tsandboxId\"p\n" + + "\x13SandboxPauseRequest\x12\x1d\n" + + "\n" + + "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" + + "\vtemplate_id\x18\x02 \x01(\tR\n" + + "templateId\x12\x19\n" + + "\bbuild_id\x18\x03 \x01(\tR\abuildId\"\xc7\x01\n" + + "\x0eRunningSandbox\x12&\n" + + "\x06config\x18\x01 \x01(\v2\x0e.SandboxConfigR\x06config\x12\x1b\n" + + "\tclient_id\x18\x02 \x01(\tR\bclientId\x129\n" + + "\n" + + "start_time\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\tstartTime\x125\n" + + "\bend_time\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\aendTime\"D\n" + + "\x13SandboxListResponse\x12-\n" + + "\tsandboxes\x18\x01 \x03(\v2\x0f.RunningSandboxR\tsandboxes\"q\n" + + "\x0fCachedBuildInfo\x12\x19\n" + + "\bbuild_id\x18\x01 \x01(\tR\abuildId\x12C\n" + + "\x0fexpiration_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x0eexpirationTime\"K\n" + + "\x1fSandboxListCachedBuildsResponse\x12(\n" + + "\x06builds\x18\x01 \x03(\v2\x10.CachedBuildInfoR\x06builds\"\x99\x04\n" + + "\x12OrchestratorStatus\x12%\n" + + "\x0eglobal_version\x18\x01 \x01(\x03R\rglobalVersion\x12+\n" + + "\x11running_sandboxes\x18\x02 \x01(\x03R\x10runningSandboxes\x12+\n" + + "\x11pending_sandboxes\x18\x04 \x01(\x03R\x10pendingSandboxes\x121\n" + + "\x14terminated_sandboxes\x18\x05 \x01(\x03R\x13terminatedSandboxes\x12#\n" + + "\rnum_sandboxes\x18\x06 \x01(\x03R\fnumSandboxes\x12\x16\n" + + "\x06status\x18\a \x01(\tR\x06status\x129\n" + + "\n" + + "updated_at\x18\b \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\x12h\n" + + "#earliest_running_sandbox_started_at\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\x1fearliestRunningSandboxStartedAt\x12m\n" + + "&most_recent_running_sandbox_updated_at\x18\n" + + " \x01(\v2\x1a.google.protobuf.TimestampR!mostRecentRunningSandboxUpdatedAt2\xb3\x03\n" + + "\x0eSandboxService\x127\n" + + "\x06Create\x12\x15.SandboxCreateRequest\x1a\x16.SandboxCreateResponse\x127\n" + + "\x06Update\x12\x15.SandboxUpdateRequest\x1a\x16.google.protobuf.Empty\x124\n" + + "\x04List\x12\x16.google.protobuf.Empty\x1a\x14.SandboxListResponse\x127\n" + + "\x06Delete\x12\x15.SandboxDeleteRequest\x1a\x16.google.protobuf.Empty\x125\n" + + "\x05Pause\x12\x14.SandboxPauseRequest\x1a\x16.google.protobuf.Empty\x12L\n" + + "\x10ListCachedBuilds\x12\x16.google.protobuf.Empty\x1a .SandboxListCachedBuildsResponse\x12;\n" + + "\fStatusReport\x12\x16.google.protobuf.Empty\x1a\x13.OrchestratorStatusB/Z-https://github.com/e2b-dev/infra/orchestratorb\x06proto3" + var ( file_orchestrator_proto_rawDescOnce sync.Once - file_orchestrator_proto_rawDescData = file_orchestrator_proto_rawDesc + file_orchestrator_proto_rawDescData []byte ) func file_orchestrator_proto_rawDescGZIP() []byte { file_orchestrator_proto_rawDescOnce.Do(func() { - file_orchestrator_proto_rawDescData = protoimpl.X.CompressGZIP(file_orchestrator_proto_rawDescData) + file_orchestrator_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_orchestrator_proto_rawDesc), len(file_orchestrator_proto_rawDesc))) }) return file_orchestrator_proto_rawDescData } -var file_orchestrator_proto_msgTypes = make([]protoimpl.MessageInfo, 12) -var file_orchestrator_proto_goTypes = []interface{}{ +var file_orchestrator_proto_msgTypes = make([]protoimpl.MessageInfo, 13) +var file_orchestrator_proto_goTypes = []any{ (*SandboxConfig)(nil), // 0: SandboxConfig (*SandboxCreateRequest)(nil), // 1: SandboxCreateRequest (*SandboxCreateResponse)(nil), // 2: SandboxCreateResponse @@ -877,41 +897,47 @@ var file_orchestrator_proto_goTypes = []interface{}{ (*SandboxListResponse)(nil), // 7: SandboxListResponse (*CachedBuildInfo)(nil), // 8: CachedBuildInfo (*SandboxListCachedBuildsResponse)(nil), // 9: SandboxListCachedBuildsResponse - nil, // 10: SandboxConfig.EnvVarsEntry - nil, // 11: SandboxConfig.MetadataEntry - (*timestamppb.Timestamp)(nil), // 12: google.protobuf.Timestamp - (*emptypb.Empty)(nil), // 13: google.protobuf.Empty + (*OrchestratorStatus)(nil), // 10: OrchestratorStatus + nil, // 11: SandboxConfig.EnvVarsEntry + nil, // 12: SandboxConfig.MetadataEntry + (*timestamppb.Timestamp)(nil), // 13: google.protobuf.Timestamp + (*emptypb.Empty)(nil), // 14: google.protobuf.Empty } var file_orchestrator_proto_depIdxs = []int32{ - 10, // 0: SandboxConfig.env_vars:type_name -> SandboxConfig.EnvVarsEntry - 11, // 1: SandboxConfig.metadata:type_name -> SandboxConfig.MetadataEntry + 11, // 0: SandboxConfig.env_vars:type_name -> SandboxConfig.EnvVarsEntry + 12, // 1: SandboxConfig.metadata:type_name -> SandboxConfig.MetadataEntry 0, // 2: SandboxCreateRequest.sandbox:type_name -> SandboxConfig - 12, // 3: SandboxCreateRequest.start_time:type_name -> google.protobuf.Timestamp - 12, // 4: SandboxCreateRequest.end_time:type_name -> google.protobuf.Timestamp - 12, // 5: SandboxUpdateRequest.end_time:type_name -> google.protobuf.Timestamp + 13, // 3: SandboxCreateRequest.start_time:type_name -> google.protobuf.Timestamp + 13, // 4: SandboxCreateRequest.end_time:type_name -> google.protobuf.Timestamp + 13, // 5: SandboxUpdateRequest.end_time:type_name -> google.protobuf.Timestamp 0, // 6: RunningSandbox.config:type_name -> SandboxConfig - 12, // 7: RunningSandbox.start_time:type_name -> google.protobuf.Timestamp - 12, // 8: RunningSandbox.end_time:type_name -> google.protobuf.Timestamp + 13, // 7: RunningSandbox.start_time:type_name -> google.protobuf.Timestamp + 13, // 8: RunningSandbox.end_time:type_name -> google.protobuf.Timestamp 6, // 9: SandboxListResponse.sandboxes:type_name -> RunningSandbox - 12, // 10: CachedBuildInfo.expiration_time:type_name -> google.protobuf.Timestamp + 13, // 10: CachedBuildInfo.expiration_time:type_name -> google.protobuf.Timestamp 8, // 11: SandboxListCachedBuildsResponse.builds:type_name -> CachedBuildInfo - 1, // 12: SandboxService.Create:input_type -> SandboxCreateRequest - 3, // 13: SandboxService.Update:input_type -> SandboxUpdateRequest - 13, // 14: SandboxService.List:input_type -> google.protobuf.Empty - 4, // 15: SandboxService.Delete:input_type -> SandboxDeleteRequest - 5, // 16: SandboxService.Pause:input_type -> SandboxPauseRequest - 13, // 17: SandboxService.ListCachedBuilds:input_type -> google.protobuf.Empty - 2, // 18: SandboxService.Create:output_type -> SandboxCreateResponse - 13, // 19: SandboxService.Update:output_type -> google.protobuf.Empty - 7, // 20: SandboxService.List:output_type -> SandboxListResponse - 13, // 21: SandboxService.Delete:output_type -> google.protobuf.Empty - 13, // 22: SandboxService.Pause:output_type -> google.protobuf.Empty - 9, // 23: SandboxService.ListCachedBuilds:output_type -> SandboxListCachedBuildsResponse - 18, // [18:24] is the sub-list for method output_type - 12, // [12:18] is the sub-list for method input_type - 12, // [12:12] is the sub-list for extension type_name - 12, // [12:12] is the sub-list for extension extendee - 0, // [0:12] is the sub-list for field type_name + 13, // 12: OrchestratorStatus.updated_at:type_name -> google.protobuf.Timestamp + 13, // 13: OrchestratorStatus.earliest_running_sandbox_started_at:type_name -> google.protobuf.Timestamp + 13, // 14: OrchestratorStatus.most_recent_running_sandbox_updated_at:type_name -> google.protobuf.Timestamp + 1, // 15: SandboxService.Create:input_type -> SandboxCreateRequest + 3, // 16: SandboxService.Update:input_type -> SandboxUpdateRequest + 14, // 17: SandboxService.List:input_type -> google.protobuf.Empty + 4, // 18: SandboxService.Delete:input_type -> SandboxDeleteRequest + 5, // 19: SandboxService.Pause:input_type -> SandboxPauseRequest + 14, // 20: SandboxService.ListCachedBuilds:input_type -> google.protobuf.Empty + 14, // 21: SandboxService.StatusReport:input_type -> google.protobuf.Empty + 2, // 22: SandboxService.Create:output_type -> SandboxCreateResponse + 14, // 23: SandboxService.Update:output_type -> google.protobuf.Empty + 7, // 24: SandboxService.List:output_type -> SandboxListResponse + 14, // 25: SandboxService.Delete:output_type -> google.protobuf.Empty + 14, // 26: SandboxService.Pause:output_type -> google.protobuf.Empty + 9, // 27: SandboxService.ListCachedBuilds:output_type -> SandboxListCachedBuildsResponse + 10, // 28: SandboxService.StatusReport:output_type -> OrchestratorStatus + 22, // [22:29] is the sub-list for method output_type + 15, // [15:22] is the sub-list for method input_type + 15, // [15:15] is the sub-list for extension type_name + 15, // [15:15] is the sub-list for extension extendee + 0, // [0:15] is the sub-list for field type_name } func init() { file_orchestrator_proto_init() } @@ -919,136 +945,14 @@ func file_orchestrator_proto_init() { if File_orchestrator_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_orchestrator_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SandboxConfig); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_orchestrator_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SandboxCreateRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_orchestrator_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SandboxCreateResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_orchestrator_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SandboxUpdateRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_orchestrator_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SandboxDeleteRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_orchestrator_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SandboxPauseRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_orchestrator_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*RunningSandbox); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_orchestrator_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SandboxListResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_orchestrator_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CachedBuildInfo); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_orchestrator_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SandboxListCachedBuildsResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - file_orchestrator_proto_msgTypes[0].OneofWrappers = []interface{}{} + file_orchestrator_proto_msgTypes[0].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_orchestrator_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_orchestrator_proto_rawDesc), len(file_orchestrator_proto_rawDesc)), NumEnums: 0, - NumMessages: 12, + NumMessages: 13, NumExtensions: 0, NumServices: 1, }, @@ -1057,7 +961,6 @@ func file_orchestrator_proto_init() { MessageInfos: file_orchestrator_proto_msgTypes, }.Build() File_orchestrator_proto = out.File - file_orchestrator_proto_rawDesc = nil file_orchestrator_proto_goTypes = nil file_orchestrator_proto_depIdxs = nil } diff --git a/packages/shared/pkg/grpc/orchestrator/orchestrator_grpc.pb.go b/packages/shared/pkg/grpc/orchestrator/orchestrator_grpc.pb.go index dfc25ec5e..ea48065d5 100644 --- a/packages/shared/pkg/grpc/orchestrator/orchestrator_grpc.pb.go +++ b/packages/shared/pkg/grpc/orchestrator/orchestrator_grpc.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.2.0 -// - protoc v5.29.3 +// - protoc-gen-go-grpc v1.5.1 +// - protoc v5.29.2 // source: orchestrator.proto package orchestrator @@ -16,8 +16,18 @@ import ( // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + SandboxService_Create_FullMethodName = "/SandboxService/Create" + SandboxService_Update_FullMethodName = "/SandboxService/Update" + SandboxService_List_FullMethodName = "/SandboxService/List" + SandboxService_Delete_FullMethodName = "/SandboxService/Delete" + SandboxService_Pause_FullMethodName = "/SandboxService/Pause" + SandboxService_ListCachedBuilds_FullMethodName = "/SandboxService/ListCachedBuilds" + SandboxService_StatusReport_FullMethodName = "/SandboxService/StatusReport" +) // SandboxServiceClient is the client API for SandboxService service. // @@ -29,6 +39,7 @@ type SandboxServiceClient interface { Delete(ctx context.Context, in *SandboxDeleteRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) Pause(ctx context.Context, in *SandboxPauseRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) ListCachedBuilds(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*SandboxListCachedBuildsResponse, error) + StatusReport(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*OrchestratorStatus, error) } type sandboxServiceClient struct { @@ -40,8 +51,9 @@ func NewSandboxServiceClient(cc grpc.ClientConnInterface) SandboxServiceClient { } func (c *sandboxServiceClient) Create(ctx context.Context, in *SandboxCreateRequest, opts ...grpc.CallOption) (*SandboxCreateResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SandboxCreateResponse) - err := c.cc.Invoke(ctx, "/SandboxService/Create", in, out, opts...) + err := c.cc.Invoke(ctx, SandboxService_Create_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } @@ -49,8 +61,9 @@ func (c *sandboxServiceClient) Create(ctx context.Context, in *SandboxCreateRequ } func (c *sandboxServiceClient) Update(ctx context.Context, in *SandboxUpdateRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, "/SandboxService/Update", in, out, opts...) + err := c.cc.Invoke(ctx, SandboxService_Update_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } @@ -58,8 +71,9 @@ func (c *sandboxServiceClient) Update(ctx context.Context, in *SandboxUpdateRequ } func (c *sandboxServiceClient) List(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*SandboxListResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SandboxListResponse) - err := c.cc.Invoke(ctx, "/SandboxService/List", in, out, opts...) + err := c.cc.Invoke(ctx, SandboxService_List_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } @@ -67,8 +81,9 @@ func (c *sandboxServiceClient) List(ctx context.Context, in *emptypb.Empty, opts } func (c *sandboxServiceClient) Delete(ctx context.Context, in *SandboxDeleteRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, "/SandboxService/Delete", in, out, opts...) + err := c.cc.Invoke(ctx, SandboxService_Delete_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } @@ -76,8 +91,9 @@ func (c *sandboxServiceClient) Delete(ctx context.Context, in *SandboxDeleteRequ } func (c *sandboxServiceClient) Pause(ctx context.Context, in *SandboxPauseRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, "/SandboxService/Pause", in, out, opts...) + err := c.cc.Invoke(ctx, SandboxService_Pause_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } @@ -85,8 +101,19 @@ func (c *sandboxServiceClient) Pause(ctx context.Context, in *SandboxPauseReques } func (c *sandboxServiceClient) ListCachedBuilds(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*SandboxListCachedBuildsResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SandboxListCachedBuildsResponse) - err := c.cc.Invoke(ctx, "/SandboxService/ListCachedBuilds", in, out, opts...) + err := c.cc.Invoke(ctx, SandboxService_ListCachedBuilds_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sandboxServiceClient) StatusReport(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*OrchestratorStatus, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(OrchestratorStatus) + err := c.cc.Invoke(ctx, SandboxService_StatusReport_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } @@ -95,7 +122,7 @@ func (c *sandboxServiceClient) ListCachedBuilds(ctx context.Context, in *emptypb // SandboxServiceServer is the server API for SandboxService service. // All implementations must embed UnimplementedSandboxServiceServer -// for forward compatibility +// for forward compatibility. type SandboxServiceServer interface { Create(context.Context, *SandboxCreateRequest) (*SandboxCreateResponse, error) Update(context.Context, *SandboxUpdateRequest) (*emptypb.Empty, error) @@ -103,12 +130,16 @@ type SandboxServiceServer interface { Delete(context.Context, *SandboxDeleteRequest) (*emptypb.Empty, error) Pause(context.Context, *SandboxPauseRequest) (*emptypb.Empty, error) ListCachedBuilds(context.Context, *emptypb.Empty) (*SandboxListCachedBuildsResponse, error) + StatusReport(context.Context, *emptypb.Empty) (*OrchestratorStatus, error) mustEmbedUnimplementedSandboxServiceServer() } -// UnimplementedSandboxServiceServer must be embedded to have forward compatible implementations. -type UnimplementedSandboxServiceServer struct { -} +// UnimplementedSandboxServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedSandboxServiceServer struct{} func (UnimplementedSandboxServiceServer) Create(context.Context, *SandboxCreateRequest) (*SandboxCreateResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Create not implemented") @@ -128,7 +159,11 @@ func (UnimplementedSandboxServiceServer) Pause(context.Context, *SandboxPauseReq func (UnimplementedSandboxServiceServer) ListCachedBuilds(context.Context, *emptypb.Empty) (*SandboxListCachedBuildsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ListCachedBuilds not implemented") } +func (UnimplementedSandboxServiceServer) StatusReport(context.Context, *emptypb.Empty) (*OrchestratorStatus, error) { + return nil, status.Errorf(codes.Unimplemented, "method StatusReport not implemented") +} func (UnimplementedSandboxServiceServer) mustEmbedUnimplementedSandboxServiceServer() {} +func (UnimplementedSandboxServiceServer) testEmbeddedByValue() {} // UnsafeSandboxServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to SandboxServiceServer will @@ -138,6 +173,13 @@ type UnsafeSandboxServiceServer interface { } func RegisterSandboxServiceServer(s grpc.ServiceRegistrar, srv SandboxServiceServer) { + // If the following call pancis, it indicates UnimplementedSandboxServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } s.RegisterService(&SandboxService_ServiceDesc, srv) } @@ -151,7 +193,7 @@ func _SandboxService_Create_Handler(srv interface{}, ctx context.Context, dec fu } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/SandboxService/Create", + FullMethod: SandboxService_Create_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SandboxServiceServer).Create(ctx, req.(*SandboxCreateRequest)) @@ -169,7 +211,7 @@ func _SandboxService_Update_Handler(srv interface{}, ctx context.Context, dec fu } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/SandboxService/Update", + FullMethod: SandboxService_Update_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SandboxServiceServer).Update(ctx, req.(*SandboxUpdateRequest)) @@ -187,7 +229,7 @@ func _SandboxService_List_Handler(srv interface{}, ctx context.Context, dec func } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/SandboxService/List", + FullMethod: SandboxService_List_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SandboxServiceServer).List(ctx, req.(*emptypb.Empty)) @@ -205,7 +247,7 @@ func _SandboxService_Delete_Handler(srv interface{}, ctx context.Context, dec fu } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/SandboxService/Delete", + FullMethod: SandboxService_Delete_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SandboxServiceServer).Delete(ctx, req.(*SandboxDeleteRequest)) @@ -223,7 +265,7 @@ func _SandboxService_Pause_Handler(srv interface{}, ctx context.Context, dec fun } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/SandboxService/Pause", + FullMethod: SandboxService_Pause_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SandboxServiceServer).Pause(ctx, req.(*SandboxPauseRequest)) @@ -241,7 +283,7 @@ func _SandboxService_ListCachedBuilds_Handler(srv interface{}, ctx context.Conte } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/SandboxService/ListCachedBuilds", + FullMethod: SandboxService_ListCachedBuilds_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SandboxServiceServer).ListCachedBuilds(ctx, req.(*emptypb.Empty)) @@ -249,6 +291,24 @@ func _SandboxService_ListCachedBuilds_Handler(srv interface{}, ctx context.Conte return interceptor(ctx, in, info, handler) } +func _SandboxService_StatusReport_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(emptypb.Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SandboxServiceServer).StatusReport(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SandboxService_StatusReport_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SandboxServiceServer).StatusReport(ctx, req.(*emptypb.Empty)) + } + return interceptor(ctx, in, info, handler) +} + // SandboxService_ServiceDesc is the grpc.ServiceDesc for SandboxService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -280,6 +340,10 @@ var SandboxService_ServiceDesc = grpc.ServiceDesc{ MethodName: "ListCachedBuilds", Handler: _SandboxService_ListCachedBuilds_Handler, }, + { + MethodName: "StatusReport", + Handler: _SandboxService_StatusReport_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "orchestrator.proto", diff --git a/sqlc.yaml b/sqlc.yaml index 615050b78..118ef7041 100644 --- a/sqlc.yaml +++ b/sqlc.yaml @@ -2,8 +2,8 @@ version: "2" sql: # ORCHESTRATOR PROCESS' LOCAL DATABASE - engine: "sqlite" - queries: "packages/orchestrator/queries.sql" - schema: "packages/orchestrator/schema.sql" + queries: "packages/orchestrator/internal/db/queries.sql" + schema: "packages/orchestrator/internal/db/schema.sql" # migrations are unnecessary right now because the DB never lives # longer than the process. gen: