|
| 1 | +package prebuilds |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "database/sql" |
| 6 | + "errors" |
| 7 | + |
| 8 | + "github.com/coder/coder/v2/coderd/prebuilds" |
| 9 | + |
| 10 | + "github.com/google/uuid" |
| 11 | + "golang.org/x/xerrors" |
| 12 | + |
| 13 | + "github.com/coder/coder/v2/coderd/database" |
| 14 | +) |
| 15 | + |
| 16 | +type EnterpriseClaimer struct{} |
| 17 | + |
| 18 | +func (_ EnterpriseClaimer) Claim(ctx context.Context, store database.Store, userID uuid.UUID, name string, presetID uuid.UUID) (*uuid.UUID, error) { |
| 19 | + var prebuildID *uuid.UUID |
| 20 | + err := store.InTx(func(db database.Store) error { |
| 21 | + // TODO: do we need this? |
| 22 | + //// Ensure no other replica can claim a prebuild for this user simultaneously. |
| 23 | + // err := store.AcquireLock(ctx, database.GenLockID(fmt.Sprintf("prebuild-user-claim-%s", userID.String()))) |
| 24 | + // if err != nil { |
| 25 | + // return xerrors.Errorf("acquire claim lock for user %q: %w", userID.String(), err) |
| 26 | + //} |
| 27 | + |
| 28 | + result, err := db.ClaimPrebuiltWorkspace(ctx, database.ClaimPrebuiltWorkspaceParams{ |
| 29 | + NewUserID: userID, |
| 30 | + NewName: name, |
| 31 | + PresetID: presetID, |
| 32 | + }) |
| 33 | + if err != nil { |
| 34 | + switch { |
| 35 | + // No eligible prebuilds found |
| 36 | + case errors.Is(err, sql.ErrNoRows): |
| 37 | + // Exit, this will result in a nil prebuildID being returned, which is fine |
| 38 | + return nil |
| 39 | + default: |
| 40 | + return xerrors.Errorf("claim prebuild for user %q: %w", userID.String(), err) |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + prebuildID = &result.ID |
| 45 | + |
| 46 | + return nil |
| 47 | + }, &database.TxOptions{ |
| 48 | + TxIdentifier: "prebuild-claim", |
| 49 | + }) |
| 50 | + |
| 51 | + return prebuildID, err |
| 52 | +} |
| 53 | + |
| 54 | +func (_ EnterpriseClaimer) Initiator() uuid.UUID { |
| 55 | + return prebuilds.SystemUserID |
| 56 | +} |
| 57 | + |
| 58 | +var _ prebuilds.Claimer = &EnterpriseClaimer{} |
0 commit comments