| 1 | package hostops |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "os" |
| 8 | |
| 9 | "github.com/carlosframework/platform/internal/provision" |
| 10 | "github.com/carlosframework/platform/internal/release" |
| 11 | ) |
| 12 | |
| 13 | func sequenceError(err error) error { |
| 14 | if errors.Is(err, provision.ErrRecordSequence) { |
| 15 | return ErrIdentity |
| 16 | } |
| 17 | if errors.Is(err, provision.ErrRecordSequenceExhausted) { |
| 18 | return ErrPending |
| 19 | } |
| 20 | return err |
| 21 | } |
| 22 | |
| 23 | func recordSequence(body []byte) (map[string]json.RawMessage, uint64, error) { |
| 24 | fields, seq, err := provision.RecordSequence(body) |
| 25 | return fields, seq, sequenceError(err) |
| 26 | } |
| 27 | |
| 28 | func advanceRecordSequence(before, body []byte) ([]byte, error) { |
| 29 | next, err := provision.AdvanceRecordSequence(before, body) |
| 30 | return next, sequenceError(err) |
| 31 | } |
| 32 | |
| 33 | // This claim-only boundary delegates encoding to provision, including when |
| 34 | // an upstream typed writer has already prepared the same conditional Put. |
| 35 | func putSequencedRecord(ctx context.Context, raw release.Store, key string, body []byte, etag string) (string, error) { |
| 36 | before, seen, err := raw.Get(ctx, key) |
| 37 | if errors.Is(err, os.ErrNotExist) { |
| 38 | if etag != "" { |
| 39 | return "", release.ErrCASConflict |
| 40 | } |
| 41 | before, seen = []byte(`{}`), "" |
| 42 | } else if err != nil { |
| 43 | return "", err |
| 44 | } |
| 45 | if seen != etag { |
| 46 | return "", release.ErrCASConflict |
| 47 | } |
| 48 | MarkAppMutationIssued(ctx) |
| 49 | tag, _, err := provision.WriteRecord(provision.WithRecordSequence(ctx), raw, key, before, body, etag) |
| 50 | return tag, sequenceError(err) |
| 51 | } |
| 52 | |