| 1 | package personapi |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/binary" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "sort" |
| 12 | "time" |
| 13 | |
| 14 | "gorm.io/gorm" |
| 15 | ) |
| 16 | |
| 17 | type Request struct { |
| 18 | Principal string `gorm:"primaryKey;not null"` |
| 19 | Operation string `gorm:"primaryKey;not null"` |
| 20 | Resource string `gorm:"primaryKey;not null"` |
| 21 | RequestID string `gorm:"primaryKey;not null"` |
| 22 | InputHash string `gorm:"not null"` |
| 23 | Result string `gorm:"not null"` |
| 24 | CreatedAt time.Time `gorm:"not null"` |
| 25 | ExpiresAt time.Time `gorm:"not null;index:person_api_requests_expiry"` |
| 26 | } |
| 27 | |
| 28 | func (Request) TableName() string { return "person_api_requests" } |
| 29 | |
| 30 | var Models = []any{&Request{}, &DeviceRecord{}, &DeviceRate{}} |
| 31 | |
| 32 | type requestKey struct{} |
| 33 | |
| 34 | func WithRequest(ctx context.Context, r Request) context.Context { |
| 35 | return context.WithValue(ctx, requestKey{}, r) |
| 36 | } |
| 37 | func RequestFrom(ctx context.Context) (Request, bool) { |
| 38 | r, ok := ctx.Value(requestKey{}).(Request) |
| 39 | return r, ok && r.RequestID != "" |
| 40 | } |
| 41 | |
| 42 | // Record adds API metadata to the application's existing transaction. Application |
| 43 | // replay records remain authoritative across browser and API requests. |
| 44 | func Record(tx *gorm.DB, ctx context.Context, conflict error) error { |
| 45 | r, ok := RequestFrom(ctx) |
| 46 | if !ok { |
| 47 | return nil |
| 48 | } |
| 49 | if err := tx.Where("expires_at <= ?", time.Now().UTC()).Delete(&Request{}).Error; err != nil { |
| 50 | return err |
| 51 | } |
| 52 | var old Request |
| 53 | err := tx.Where("principal=? AND operation=? AND resource=? AND request_id=?", r.Principal, r.Operation, r.Resource, r.RequestID).Take(&old).Error |
| 54 | if err == nil { |
| 55 | if old.InputHash != r.InputHash { |
| 56 | return conflict |
| 57 | } |
| 58 | return nil |
| 59 | } |
| 60 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 61 | return err |
| 62 | } |
| 63 | r.CreatedAt = time.Now().UTC() |
| 64 | r.ExpiresAt = r.CreatedAt.Add(30 * 24 * time.Hour) |
| 65 | return tx.Create(&r).Error |
| 66 | } |
| 67 | |
| 68 | // Replay is used after the legacy operation's current authority checks. |
| 69 | func Replay(tx *gorm.DB, ctx context.Context, out any, conflict error) (bool, error) { |
| 70 | r, ok := RequestFrom(ctx) |
| 71 | if !ok { |
| 72 | return false, nil |
| 73 | } |
| 74 | var old Request |
| 75 | err := tx.Where("principal=? AND operation=? AND resource=? AND request_id=?", r.Principal, r.Operation, r.Resource, r.RequestID).Take(&old).Error |
| 76 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 77 | return false, nil |
| 78 | } |
| 79 | if err != nil { |
| 80 | return false, err |
| 81 | } |
| 82 | if !time.Now().Before(old.ExpiresAt) { |
| 83 | return false, nil |
| 84 | } |
| 85 | if old.InputHash != r.InputHash { |
| 86 | return false, conflict |
| 87 | } |
| 88 | if old.Result == "" { |
| 89 | return false, nil |
| 90 | } |
| 91 | return true, json.Unmarshal([]byte(old.Result), out) |
| 92 | } |
| 93 | func SaveResult(tx *gorm.DB, ctx context.Context, out any, conflict error) error { |
| 94 | if err := Record(tx, ctx, conflict); err != nil { |
| 95 | return err |
| 96 | } |
| 97 | r, ok := RequestFrom(ctx) |
| 98 | if !ok { |
| 99 | return nil |
| 100 | } |
| 101 | b, err := json.Marshal(out) |
| 102 | if err != nil { |
| 103 | return err |
| 104 | } |
| 105 | return tx.Model(&Request{}).Where("principal=? AND operation=? AND resource=? AND request_id=?", r.Principal, r.Operation, r.Resource, r.RequestID).Select("result").Update("result", string(b)).Error |
| 106 | } |
| 107 | func Revision(v any) int64 { |
| 108 | b, _ := json.Marshal(v) |
| 109 | sum := sha256.Sum256(b) |
| 110 | return int64(binary.BigEndian.Uint64(sum[:8])>>1) | 1 |
| 111 | } |
| 112 | func Paginate(codec kernel.CursorCodec, principal, scope, cursor string, limit int, in Result, expired error) (Result, error) { |
| 113 | var items []json.RawMessage |
| 114 | values := in.Value |
| 115 | positions := map[string]listPosition{} |
| 116 | if ordered, ok := values.(orderedItems); ok { |
| 117 | values, positions = ordered.Values, ordered.Positions |
| 118 | } |
| 119 | raw, err := json.Marshal(values) |
| 120 | if err != nil { |
| 121 | return Result{}, err |
| 122 | } |
| 123 | if err = json.Unmarshal(raw, &items); err != nil { |
| 124 | return Result{}, err |
| 125 | } |
| 126 | if items == nil { |
| 127 | items = []json.RawMessage{} |
| 128 | } |
| 129 | type entry struct { |
| 130 | key listPosition |
| 131 | value json.RawMessage |
| 132 | } |
| 133 | entries := make([]entry, 0, len(items)) |
| 134 | for _, item := range items { |
| 135 | var key struct { |
| 136 | ID string `json:"id"` |
| 137 | Address string `json:"address"` |
| 138 | } |
| 139 | if err = json.Unmarshal(item, &key); err != nil { |
| 140 | return Result{}, err |
| 141 | } |
| 142 | k := key.ID |
| 143 | if scope == "people" || scope == "roster" { |
| 144 | k = key.Address |
| 145 | } |
| 146 | if k == "" { |
| 147 | return Result{}, errors.New("missing pagination key") |
| 148 | } |
| 149 | position := positions[k] |
| 150 | position.ID = k |
| 151 | entries = append(entries, entry{position, item}) |
| 152 | } |
| 153 | sort.Slice(entries, func(i, j int) bool { return entries[i].key.before(entries[j].key) }) |
| 154 | binding := principal + "\x00" + scope |
| 155 | var after listPosition |
| 156 | if cursor != "" { |
| 157 | if err = codec.Open(binding, cursor, &after); err != nil { |
| 158 | return Result{}, expired |
| 159 | } |
| 160 | } |
| 161 | revision := in.Revision |
| 162 | if revision < 1 { |
| 163 | revision = Revision(values) |
| 164 | } |
| 165 | out := Page[json.RawMessage]{Items: []json.RawMessage{}, Revision: revision} |
| 166 | for i, e := range entries { |
| 167 | if cursor != "" && !after.before(e.key) { |
| 168 | continue |
| 169 | } |
| 170 | out.Items = append(out.Items, e.value) |
| 171 | if len(out.Items) == limit { |
| 172 | if i < len(entries)-1 { |
| 173 | out.NextCursor, err = codec.Seal(binding, e.key) |
| 174 | } |
| 175 | break |
| 176 | } |
| 177 | } |
| 178 | return Result{out, revision}, err |
| 179 | } |
| 180 | |
| 181 | func CanonicalHash(input any) (string, error) { |
| 182 | raw, err := json.Marshal(input) |
| 183 | if err != nil { |
| 184 | return "", err |
| 185 | } |
| 186 | d := json.NewDecoder(bytes.NewReader(raw)) |
| 187 | d.UseNumber() |
| 188 | var value any |
| 189 | if err = d.Decode(&value); err != nil { |
| 190 | return "", err |
| 191 | } |
| 192 | return kernel.InputHash(value) |
| 193 | } |
| 194 | |
| 195 | func WithoutRequest(ctx context.Context) context.Context { |
| 196 | return context.WithValue(ctx, requestKey{}, Request{}) |
| 197 | } |
| 198 | |
| 199 | // ApplicationRequest keeps direct and HTTP mutations on the same replay key. |
| 200 | func ApplicationRequest(ctx context.Context, a kernel.Actor, op, id string, input any, m kernel.Mutation) (context.Context, error) { |
| 201 | hash, err := CanonicalHash(input) |
| 202 | if err != nil { |
| 203 | return ctx, err |
| 204 | } |
| 205 | return WithRequest(ctx, Request{Principal: a.Address, Operation: op, Resource: id, RequestID: m.RequestID, InputHash: hash}), nil |
| 206 | } |
| 207 | |