• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

sapcc / limes / 16296120355

15 Jul 2025 02:28PM UTC coverage: 78.675% (+0.2%) from 78.476%
16296120355

Pull #741

github

wagnerd3
PR adjustments round 1: DB + model
Pull Request #741: project_v2 table DB schema migrations

414 of 463 new or added lines in 18 files covered. (89.42%)

11 existing lines in 6 files now uncovered.

6840 of 8694 relevant lines covered (78.67%)

57.07 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.64
/internal/api/commitment.go
1
// SPDX-FileCopyrightText: 2023 SAP SE or an SAP affiliate company
2
// SPDX-License-Identifier: Apache-2.0
3

4
package api
5

6
import (
7
        "cmp"
8
        "database/sql"
9
        "encoding/json"
10
        "errors"
11
        "fmt"
12
        "maps"
13
        "net/http"
14
        "slices"
15
        "strings"
16
        "time"
17

18
        "github.com/gorilla/mux"
19
        . "github.com/majewsky/gg/option"
20
        "github.com/majewsky/gg/options"
21
        "github.com/sapcc/go-api-declarations/cadf"
22
        "github.com/sapcc/go-api-declarations/limes"
23
        limesresources "github.com/sapcc/go-api-declarations/limes/resources"
24
        "github.com/sapcc/go-api-declarations/liquid"
25
        "github.com/sapcc/go-bits/audittools"
26
        "github.com/sapcc/go-bits/errext"
27
        "github.com/sapcc/go-bits/gopherpolicy"
28
        "github.com/sapcc/go-bits/httpapi"
29
        "github.com/sapcc/go-bits/must"
30
        "github.com/sapcc/go-bits/respondwith"
31
        "github.com/sapcc/go-bits/sqlext"
32

33
        "github.com/sapcc/limes/internal/core"
34
        "github.com/sapcc/limes/internal/datamodel"
35
        "github.com/sapcc/limes/internal/db"
36
        "github.com/sapcc/limes/internal/reports"
37
)
38

39
var (
40
        getProjectCommitmentsQuery = sqlext.SimplifyWhitespace(`
41
                SELECT pc.*
42
                  FROM project_commitments_v2 pc
43
                  JOIN cluster_az_resources cazr ON pc.az_resource_id = cazr.id
44
                  JOIN cluster_resources cr ON cazr.resource_id = cr.id {{AND cr.name = $resource_name}}
45
                  JOIN cluster_services cs ON cr.service_id = cs.id {{AND cs.type = $service_type}}
46
                 WHERE %s AND pc.state NOT IN ('superseded', 'expired')
47
                 ORDER BY pc.id
48
        `)
49

50
        getClusterAZResourceLocationsQuery = sqlext.SimplifyWhitespace(`
51
                SELECT cazr.id, cs.type, cr.name, cazr.az
52
                  FROM project_az_resources_v2 pazr
53
                  JOIN cluster_az_resources cazr on pazr.az_resource_id = cazr.id
54
                  JOIN cluster_resources cr ON cazr.resource_id = cr.id {{AND cr.name = $resource_name}}
55
                  JOIN cluster_services cs ON cr.service_id = cs.id {{AND cs.type = $service_type}}
56
                 WHERE %s
57
        `)
58

59
        findProjectCommitmentByIDQuery = sqlext.SimplifyWhitespace(`
60
                SELECT pc.*
61
                  FROM project_commitments_v2 pc
62
                 WHERE pc.id = $1 AND pc.project_id = $2
63
        `)
64

65
        // NOTE: The third output column is `resourceAllowsCommitments`.
66
        findClusterAZResourceIDByLocationQuery = sqlext.SimplifyWhitespace(`
67
                SELECT pr.id, cazr.id, pr.forbidden IS NOT TRUE
68
                  FROM cluster_az_resources cazr
69
                  JOIN cluster_resources cr ON cazr.resource_id = cr.id
70
                  JOIN cluster_services cs ON cr.service_id = cs.id
71
                  JOIN project_resources_v2 pr ON pr.resource_id = cr.id
72
                 WHERE pr.project_id = $1 AND cs.type = $2 AND cr.name = $3 AND cazr.az = $4
73
        `)
74

75
        findClusterAZResourceLocationByIDQuery = sqlext.SimplifyWhitespace(`
76
                SELECT cs.type, cr.name, cazr.az
77
                  FROM cluster_az_resources cazr
78
                  JOIN cluster_resources cr ON cazr.resource_id = cr.id
79
                  JOIN cluster_services cs ON cr.service_id = cs.id
80
                 WHERE cazr.id = $1
81
        `)
82
        getCommitmentWithMatchingTransferTokenQuery = sqlext.SimplifyWhitespace(`
83
                SELECT * FROM project_commitments_v2 WHERE id = $1 AND transfer_token = $2
84
        `)
85
        findCommitmentByTransferToken = sqlext.SimplifyWhitespace(`
86
                SELECT * FROM project_commitments_v2 WHERE transfer_token = $1
87
        `)
88
        findTargetProjectResourceBySourceIDQuery = sqlext.SimplifyWhitespace(`
89
                WITH source as (
90
                SELECT pr.id AS project_resource_id, cazr.id AS az_resource_id
91
                  FROM project_commitments_v2 pc
92
                  JOIN cluster_az_resources cazr ON pc.az_resource_id = cazr.id
93
                  JOIN project_resources_v2 pr ON pr.resource_id = cazr.resource_id AND pr.project_id = pc.project_id
94
                WHERE pc.id = $1
95
                )
96
                SELECT s.project_resource_id, pr.id
97
                  FROM cluster_az_resources cazr
98
                  JOIN project_resources_v2 pr ON pr.resource_id = cazr.resource_id
99
                  JOIN source s ON cazr.id = s.az_resource_id
100
                 WHERE pr.project_id = $2
101
        `)
102
        findTargetClusterAZResourceByTargetProjectQuery = sqlext.SimplifyWhitespace(`
103
                SELECT pr.id, cazr.id
104
                  FROM project_az_resources_v2 pazr
105
                  JOIN cluster_az_resources cazr ON pazr.az_resource_id = cazr.id
106
                  JOIN cluster_resources cr ON cazr.resource_id = cr.id
107
                  JOIN cluster_services cs ON cr.service_id = cs.id
108
                  JOIN project_resources_v2 pr ON pr.resource_id = cr.id AND pr.project_id = pazr.project_id
109
                 WHERE pazr.project_id = $1 AND cs.type = $2 AND cr.name = $3 AND cazr.az = $4
110
        `)
111
)
112

113
// GetProjectCommitments handles GET /v1/domains/:domain_id/projects/:project_id/commitments.
114
func (p *v1Provider) GetProjectCommitments(w http.ResponseWriter, r *http.Request) {
15✔
115
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments")
15✔
116
        token := p.CheckToken(r)
15✔
117
        if !token.Require(w, "project:show") {
16✔
118
                return
1✔
119
        }
1✔
120
        dbDomain := p.FindDomainFromRequest(w, r)
14✔
121
        if dbDomain == nil {
15✔
122
                return
1✔
123
        }
1✔
124
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
13✔
125
        if dbProject == nil {
14✔
126
                return
1✔
127
        }
1✔
128
        serviceInfos, err := p.Cluster.AllServiceInfos()
12✔
129
        if respondwith.ErrorText(w, err) {
12✔
130
                return
×
131
        }
×
132

133
        // enumerate project AZ resources
134
        filter := reports.ReadFilter(r, p.Cluster, serviceInfos)
12✔
135
        queryStr, joinArgs := filter.PrepareQuery(getClusterAZResourceLocationsQuery)
12✔
136
        whereStr, whereArgs := db.BuildSimpleWhereClause(map[string]any{"pazr.project_id": dbProject.ID}, len(joinArgs))
12✔
137
        azResourceLocationsByID := make(map[db.ClusterAZResourceID]core.AZResourceLocation)
12✔
138
        err = sqlext.ForeachRow(p.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {
137✔
139
                var (
125✔
140
                        id  db.ClusterAZResourceID
125✔
141
                        loc core.AZResourceLocation
125✔
142
                )
125✔
143
                err := rows.Scan(&id, &loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
125✔
144
                if err != nil {
125✔
145
                        return err
×
146
                }
×
147
                // this check is defense in depth (the DB should be consistent with our config)
148
                if core.HasResource(serviceInfos, loc.ServiceType, loc.ResourceName) {
250✔
149
                        azResourceLocationsByID[id] = loc
125✔
150
                }
125✔
151
                return nil
125✔
152
        })
153
        if respondwith.ErrorText(w, err) {
12✔
154
                return
×
155
        }
×
156

157
        // enumerate relevant project commitments
158
        queryStr, joinArgs = filter.PrepareQuery(getProjectCommitmentsQuery)
12✔
159
        whereStr, whereArgs = db.BuildSimpleWhereClause(map[string]any{"pc.project_id": dbProject.ID}, len(joinArgs))
12✔
160
        var dbCommitments []db.ProjectCommitmentV2
12✔
161
        _, err = p.DB.Select(&dbCommitments, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...)...)
12✔
162
        if respondwith.ErrorText(w, err) {
12✔
163
                return
×
164
        }
×
165

166
        // render response
167
        result := make([]limesresources.Commitment, 0, len(dbCommitments))
12✔
168
        for _, c := range dbCommitments {
26✔
169
                loc, exists := azResourceLocationsByID[c.AZResourceID]
14✔
170
                if !exists {
14✔
171
                        // defense in depth (the DB should not change that much between those two queries above)
×
172
                        continue
×
173
                }
174
                serviceInfo := core.InfoForService(serviceInfos, loc.ServiceType)
14✔
175
                resInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
14✔
176
                result = append(result, p.convertCommitmentToDisplayForm(c, loc, token, resInfo.Unit))
14✔
177
        }
178

179
        respondwith.JSON(w, http.StatusOK, map[string]any{"commitments": result})
12✔
180
}
181

182
func (p *v1Provider) convertCommitmentToDisplayForm(c db.ProjectCommitmentV2, loc core.AZResourceLocation, token *gopherpolicy.Token, unit limes.Unit) limesresources.Commitment {
59✔
183
        apiIdentity := p.Cluster.BehaviorForResource(loc.ServiceType, loc.ResourceName).IdentityInV1API
59✔
184
        return limesresources.Commitment{
59✔
185
                ID:               int64(c.ID),
59✔
186
                UUID:             string(c.UUID),
59✔
187
                ServiceType:      apiIdentity.ServiceType,
59✔
188
                ResourceName:     apiIdentity.Name,
59✔
189
                AvailabilityZone: loc.AvailabilityZone,
59✔
190
                Amount:           c.Amount,
59✔
191
                Unit:             unit,
59✔
192
                Duration:         c.Duration,
59✔
193
                CreatedAt:        limes.UnixEncodedTime{Time: c.CreatedAt},
59✔
194
                CreatorUUID:      c.CreatorUUID,
59✔
195
                CreatorName:      c.CreatorName,
59✔
196
                CanBeDeleted:     p.canDeleteCommitment(token, c),
59✔
197
                ConfirmBy:        options.Map(c.ConfirmBy, intoUnixEncodedTime).AsPointer(),
59✔
198
                ConfirmedAt:      options.Map(c.ConfirmedAt, intoUnixEncodedTime).AsPointer(),
59✔
199
                ExpiresAt:        limes.UnixEncodedTime{Time: c.ExpiresAt},
59✔
200
                TransferStatus:   c.TransferStatus,
59✔
201
                TransferToken:    c.TransferToken.AsPointer(),
59✔
202
                NotifyOnConfirm:  c.NotifyOnConfirm,
59✔
203
                WasRenewed:       c.RenewContextJSON.IsSome(),
59✔
204
        }
59✔
205
}
59✔
206

207
// parseAndValidateCommitmentRequest parses and validates the request body for a commitment creation or confirmation.
208
// This function in its current form should only be used if the serviceInfo is not necessary to be used outside
209
// of this validation to avoid unnecessary database queries.
210
func (p *v1Provider) parseAndValidateCommitmentRequest(w http.ResponseWriter, r *http.Request, dbDomain db.Domain) (*limesresources.CommitmentRequest, *core.AZResourceLocation, *core.ScopedCommitmentBehavior) {
46✔
211
        // parse request
46✔
212
        var parseTarget struct {
46✔
213
                Request limesresources.CommitmentRequest `json:"commitment"`
46✔
214
        }
46✔
215
        if !RequireJSON(w, r, &parseTarget) {
47✔
216
                return nil, nil, nil
1✔
217
        }
1✔
218
        req := parseTarget.Request
45✔
219

45✔
220
        // validate request
45✔
221
        serviceInfos, err := p.Cluster.AllServiceInfos()
45✔
222
        if respondwith.ErrorText(w, err) {
45✔
223
                return nil, nil, nil
×
224
        }
×
225
        nm := core.BuildResourceNameMapping(p.Cluster, serviceInfos)
45✔
226
        dbServiceType, dbResourceName, ok := nm.MapFromV1API(req.ServiceType, req.ResourceName)
45✔
227
        if !ok {
47✔
228
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", req.ServiceType, req.ResourceName)
2✔
229
                http.Error(w, msg, http.StatusUnprocessableEntity)
2✔
230
                return nil, nil, nil
2✔
231
        }
2✔
232
        behavior := p.Cluster.CommitmentBehaviorForResource(dbServiceType, dbResourceName).ForDomain(dbDomain.Name)
43✔
233
        serviceInfo := core.InfoForService(serviceInfos, dbServiceType)
43✔
234
        resInfo := core.InfoForResource(serviceInfo, dbResourceName)
43✔
235
        if len(behavior.Durations) == 0 {
44✔
236
                http.Error(w, "commitments are not enabled for this resource", http.StatusUnprocessableEntity)
1✔
237
                return nil, nil, nil
1✔
238
        }
1✔
239
        if resInfo.Topology == liquid.FlatTopology {
45✔
240
                if req.AvailabilityZone != limes.AvailabilityZoneAny {
4✔
241
                        http.Error(w, `resource does not accept AZ-aware commitments, so the AZ must be set to "any"`, http.StatusUnprocessableEntity)
1✔
242
                        return nil, nil, nil
1✔
243
                }
1✔
244
        } else {
39✔
245
                if !slices.Contains(p.Cluster.Config.AvailabilityZones, req.AvailabilityZone) {
43✔
246
                        http.Error(w, "no such availability zone", http.StatusUnprocessableEntity)
4✔
247
                        return nil, nil, nil
4✔
248
                }
4✔
249
        }
250
        if !slices.Contains(behavior.Durations, req.Duration) {
38✔
251
                buf := must.Return(json.Marshal(behavior.Durations)) // panic on error is acceptable here, marshals should never fail
1✔
252
                msg := "unacceptable commitment duration for this resource, acceptable values: " + string(buf)
1✔
253
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
254
                return nil, nil, nil
1✔
255
        }
1✔
256
        if req.Amount == 0 {
37✔
257
                http.Error(w, "amount of committed resource must be greater than zero", http.StatusUnprocessableEntity)
1✔
258
                return nil, nil, nil
1✔
259
        }
1✔
260

261
        loc := core.AZResourceLocation{
35✔
262
                ServiceType:      dbServiceType,
35✔
263
                ResourceName:     dbResourceName,
35✔
264
                AvailabilityZone: req.AvailabilityZone,
35✔
265
        }
35✔
266
        return &req, &loc, &behavior
35✔
267
}
268

269
// CanConfirmNewProjectCommitment handles POST /v1/domains/:domain_id/projects/:project_id/commitments/can-confirm.
270
func (p *v1Provider) CanConfirmNewProjectCommitment(w http.ResponseWriter, r *http.Request) {
7✔
271
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/can-confirm")
7✔
272
        token := p.CheckToken(r)
7✔
273
        if !token.Require(w, "project:edit") {
7✔
274
                return
×
275
        }
×
276
        dbDomain := p.FindDomainFromRequest(w, r)
7✔
277
        if dbDomain == nil {
7✔
278
                return
×
279
        }
×
280
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
7✔
281
        if dbProject == nil {
7✔
282
                return
×
283
        }
×
284
        req, loc, behavior := p.parseAndValidateCommitmentRequest(w, r, *dbDomain)
7✔
285
        if req == nil {
7✔
286
                return
×
287
        }
×
288

289
        var (
7✔
290
                resourceID                db.ProjectResourceID
7✔
291
                azResourceID              db.ClusterAZResourceID
7✔
292
                resourceAllowsCommitments bool
7✔
293
        )
7✔
294
        err := p.DB.QueryRow(findClusterAZResourceIDByLocationQuery, dbProject.ID, loc.ServiceType, loc.ResourceName, loc.AvailabilityZone).
7✔
295
                Scan(&resourceID, &azResourceID, &resourceAllowsCommitments)
7✔
296
        if respondwith.ErrorText(w, err) {
7✔
297
                return
×
298
        }
×
299
        if !resourceAllowsCommitments {
7✔
300
                msg := fmt.Sprintf("resource %s/%s is not enabled in this project", req.ServiceType, req.ResourceName)
×
301
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
302
                return
×
303
        }
×
304
        _ = azResourceID // returned by the above query, but not used in this function
7✔
305

7✔
306
        // commitments can never be confirmed immediately if we are before the min_confirm_date
7✔
307
        now := p.timeNow()
7✔
308
        if !behavior.CanConfirmCommitmentsAt(now) {
8✔
309
                respondwith.JSON(w, http.StatusOK, map[string]bool{"result": false})
1✔
310
                return
1✔
311
        }
1✔
312

313
        // check for committable capacity
314
        result, err := datamodel.CanConfirmNewCommitment(*loc, resourceID, req.Amount, p.Cluster, p.DB)
6✔
315
        if respondwith.ErrorText(w, err) {
6✔
316
                return
×
317
        }
×
318
        respondwith.JSON(w, http.StatusOK, map[string]bool{"result": result})
6✔
319
}
320

321
// CreateProjectCommitment handles POST /v1/domains/:domain_id/projects/:project_id/commitments/new.
322
func (p *v1Provider) CreateProjectCommitment(w http.ResponseWriter, r *http.Request) {
42✔
323
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/new")
42✔
324
        token := p.CheckToken(r)
42✔
325
        if !token.Require(w, "project:edit") {
43✔
326
                return
1✔
327
        }
1✔
328
        dbDomain := p.FindDomainFromRequest(w, r)
41✔
329
        if dbDomain == nil {
42✔
330
                return
1✔
331
        }
1✔
332
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
40✔
333
        if dbProject == nil {
41✔
334
                return
1✔
335
        }
1✔
336
        req, loc, behavior := p.parseAndValidateCommitmentRequest(w, r, *dbDomain)
39✔
337
        if req == nil {
50✔
338
                return
11✔
339
        }
11✔
340

341
        var (
28✔
342
                resourceID                db.ProjectResourceID
28✔
343
                azResourceID              db.ClusterAZResourceID
28✔
344
                resourceAllowsCommitments bool
28✔
345
        )
28✔
346
        err := p.DB.QueryRow(findClusterAZResourceIDByLocationQuery, dbProject.ID, loc.ServiceType, loc.ResourceName, loc.AvailabilityZone).
28✔
347
                Scan(&resourceID, &azResourceID, &resourceAllowsCommitments)
28✔
348
        if respondwith.ErrorText(w, err) {
28✔
349
                return
×
350
        }
×
351
        if !resourceAllowsCommitments {
29✔
352
                msg := fmt.Sprintf("resource %s/%s is not enabled in this project", req.ServiceType, req.ResourceName)
1✔
353
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
354
                return
1✔
355
        }
1✔
356

357
        // if given, confirm_by must definitely after time.Now(), and also after the MinConfirmDate if configured
358
        now := p.timeNow()
27✔
359
        if req.ConfirmBy != nil && req.ConfirmBy.Before(now) {
28✔
360
                http.Error(w, "confirm_by must not be set in the past", http.StatusUnprocessableEntity)
1✔
361
                return
1✔
362
        }
1✔
363
        if minConfirmBy, ok := behavior.MinConfirmDate.Unpack(); ok && minConfirmBy.After(now) {
31✔
364
                if req.ConfirmBy == nil || req.ConfirmBy.Before(minConfirmBy) {
6✔
365
                        msg := "this commitment needs a `confirm_by` timestamp at or after " + minConfirmBy.Format(time.RFC3339)
1✔
366
                        http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
367
                        return
1✔
368
                }
1✔
369
        }
370

371
        // we want to validate committable capacity in the same transaction that creates the commitment
372
        tx, err := p.DB.Begin()
25✔
373
        if respondwith.ErrorText(w, err) {
25✔
374
                return
×
375
        }
×
376
        defer sqlext.RollbackUnlessCommitted(tx)
25✔
377

25✔
378
        // prepare commitment
25✔
379
        confirmBy := options.Map(options.FromPointer(req.ConfirmBy), fromUnixEncodedTime)
25✔
380
        creationContext := db.CommitmentWorkflowContext{Reason: db.CommitmentReasonCreate}
25✔
381
        buf, err := json.Marshal(creationContext)
25✔
382
        if respondwith.ErrorText(w, err) {
25✔
383
                return
×
384
        }
×
385
        dbCommitment := db.ProjectCommitmentV2{
25✔
386
                UUID:                p.generateProjectCommitmentUUID(),
25✔
387
                AZResourceID:        azResourceID,
25✔
388
                ProjectID:           dbProject.ID,
25✔
389
                Amount:              req.Amount,
25✔
390
                Duration:            req.Duration,
25✔
391
                CreatedAt:           now,
25✔
392
                CreatorUUID:         token.UserUUID(),
25✔
393
                CreatorName:         fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
25✔
394
                ConfirmBy:           confirmBy,
25✔
395
                ConfirmedAt:         None[time.Time](), // may be set below
25✔
396
                ExpiresAt:           req.Duration.AddTo(confirmBy.UnwrapOr(now)),
25✔
397
                CreationContextJSON: json.RawMessage(buf),
25✔
398
        }
25✔
399
        if req.NotifyOnConfirm && req.ConfirmBy == nil {
26✔
400
                http.Error(w, "notification on confirm cannot be set for commitments with immediate confirmation", http.StatusConflict)
1✔
401
                return
1✔
402
        }
1✔
403
        dbCommitment.NotifyOnConfirm = req.NotifyOnConfirm
24✔
404

24✔
405
        if req.ConfirmBy == nil {
42✔
406
                // if not planned for confirmation in the future, confirm immediately (or fail)
18✔
407
                ok, err := datamodel.CanConfirmNewCommitment(*loc, resourceID, req.Amount, p.Cluster, tx)
18✔
408
                if respondwith.ErrorText(w, err) {
18✔
409
                        return
×
410
                }
×
411
                if !ok {
18✔
412
                        http.Error(w, "not enough capacity available for immediate confirmation", http.StatusConflict)
×
413
                        return
×
414
                }
×
415
                dbCommitment.ConfirmedAt = Some(now)
18✔
416
                dbCommitment.State = db.CommitmentStateActive
18✔
417
        } else {
6✔
418
                dbCommitment.State = db.CommitmentStatePlanned
6✔
419
        }
6✔
420

421
        // create commitment
422
        err = tx.Insert(&dbCommitment)
24✔
423
        if respondwith.ErrorText(w, err) {
24✔
424
                return
×
425
        }
×
426
        err = tx.Commit()
24✔
427
        if respondwith.ErrorText(w, err) {
24✔
428
                return
×
429
        }
×
430
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
24✔
431
        if respondwith.ErrorText(w, err) {
24✔
432
                return
×
433
        }
×
434
        serviceInfo, ok := maybeServiceInfo.Unpack()
24✔
435
        if !ok {
24✔
436
                http.Error(w, "service not found", http.StatusNotFound)
×
437
                return
×
438
        }
×
439
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
24✔
440
        commitment := p.convertCommitmentToDisplayForm(dbCommitment, *loc, token, resourceInfo.Unit)
24✔
441
        p.auditor.Record(audittools.Event{
24✔
442
                Time:       now,
24✔
443
                Request:    r,
24✔
444
                User:       token,
24✔
445
                ReasonCode: http.StatusCreated,
24✔
446
                Action:     cadf.CreateAction,
24✔
447
                Target: commitmentEventTarget{
24✔
448
                        DomainID:        dbDomain.UUID,
24✔
449
                        DomainName:      dbDomain.Name,
24✔
450
                        ProjectID:       dbProject.UUID,
24✔
451
                        ProjectName:     dbProject.Name,
24✔
452
                        Commitments:     []limesresources.Commitment{commitment},
24✔
453
                        WorkflowContext: Some(creationContext),
24✔
454
                },
24✔
455
        })
24✔
456

24✔
457
        // if the commitment is immediately confirmed, trigger a capacity scrape in
24✔
458
        // order to ApplyComputedProjectQuotas based on the new commitment
24✔
459
        if dbCommitment.ConfirmedAt.IsSome() {
42✔
460
                _, err := p.DB.Exec(`UPDATE cluster_services SET next_scrape_at = $1 WHERE type = $2`, now, loc.ServiceType)
18✔
461
                if respondwith.ErrorText(w, err) {
18✔
462
                        return
×
463
                }
×
464
        }
465

466
        // display the possibly confirmed commitment to the user
467
        err = p.DB.SelectOne(&dbCommitment, `SELECT * FROM project_commitments_v2 WHERE id = $1`, dbCommitment.ID)
24✔
468
        if respondwith.ErrorText(w, err) {
24✔
469
                return
×
470
        }
×
471

472
        respondwith.JSON(w, http.StatusCreated, map[string]any{"commitment": commitment})
24✔
473
}
474

475
// MergeProjectCommitments handles POST /v1/domains/:domain_id/projects/:project_id/commitments/merge.
476
func (p *v1Provider) MergeProjectCommitments(w http.ResponseWriter, r *http.Request) {
12✔
477
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/merge")
12✔
478
        token := p.CheckToken(r)
12✔
479
        if !token.Require(w, "project:edit") {
13✔
480
                return
1✔
481
        }
1✔
482
        dbDomain := p.FindDomainFromRequest(w, r)
11✔
483
        if dbDomain == nil {
12✔
484
                return
1✔
485
        }
1✔
486
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
10✔
487
        if dbProject == nil {
11✔
488
                return
1✔
489
        }
1✔
490
        var parseTarget struct {
9✔
491
                CommitmentIDs []db.ProjectCommitmentID `json:"commitment_ids"`
9✔
492
        }
9✔
493
        if !RequireJSON(w, r, &parseTarget) {
9✔
494
                return
×
495
        }
×
496
        commitmentIDs := parseTarget.CommitmentIDs
9✔
497
        if len(commitmentIDs) < 2 {
10✔
498
                http.Error(w, fmt.Sprintf("merging requires at least two commitments, but %d were given", len(commitmentIDs)), http.StatusBadRequest)
1✔
499
                return
1✔
500
        }
1✔
501

502
        // Load commitments
503
        dbCommitments := make([]db.ProjectCommitmentV2, len(commitmentIDs))
8✔
504
        commitmentUUIDs := make([]db.ProjectCommitmentUUID, len(commitmentIDs))
8✔
505
        for i, commitmentID := range commitmentIDs {
24✔
506
                err := p.DB.SelectOne(&dbCommitments[i], findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
16✔
507
                if errors.Is(err, sql.ErrNoRows) {
17✔
508
                        http.Error(w, "no such commitment", http.StatusNotFound)
1✔
509
                        return
1✔
510
                } else if respondwith.ErrorText(w, err) {
16✔
511
                        return
×
512
                }
×
513
                commitmentUUIDs[i] = dbCommitments[i].UUID
15✔
514
        }
515

516
        // Verify that all commitments agree on resource and AZ and are active
517
        azResourceID := dbCommitments[0].AZResourceID
7✔
518
        for _, dbCommitment := range dbCommitments {
21✔
519
                if dbCommitment.AZResourceID != azResourceID {
16✔
520
                        http.Error(w, "all commitments must be on the same resource and AZ", http.StatusConflict)
2✔
521
                        return
2✔
522
                }
2✔
523
                if dbCommitment.State != db.CommitmentStateActive {
16✔
524
                        http.Error(w, "only active commitments may be merged", http.StatusConflict)
4✔
525
                        return
4✔
526
                }
4✔
527
        }
528

529
        var loc core.AZResourceLocation
1✔
530
        err := p.DB.QueryRow(findClusterAZResourceLocationByIDQuery, azResourceID).
1✔
531
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
1✔
532
        if errors.Is(err, sql.ErrNoRows) {
1✔
533
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
534
                return
×
535
        } else if respondwith.ErrorText(w, err) {
1✔
536
                return
×
537
        }
×
538

539
        // Start transaction for creating new commitment and marking merged commitments as superseded
540
        tx, err := p.DB.Begin()
1✔
541
        if respondwith.ErrorText(w, err) {
1✔
542
                return
×
543
        }
×
544
        defer sqlext.RollbackUnlessCommitted(tx)
1✔
545

1✔
546
        // Create merged template
1✔
547
        now := p.timeNow()
1✔
548
        dbMergedCommitment := db.ProjectCommitmentV2{
1✔
549
                UUID:         p.generateProjectCommitmentUUID(),
1✔
550
                ProjectID:    dbProject.ID,
1✔
551
                AZResourceID: azResourceID,
1✔
552
                Amount:       0,                                   // overwritten below
1✔
553
                Duration:     limesresources.CommitmentDuration{}, // overwritten below
1✔
554
                CreatedAt:    now,
1✔
555
                CreatorUUID:  token.UserUUID(),
1✔
556
                CreatorName:  fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
1✔
557
                ConfirmedAt:  Some(now),
1✔
558
                ExpiresAt:    time.Time{}, // overwritten below
1✔
559
                State:        db.CommitmentStateActive,
1✔
560
        }
1✔
561

1✔
562
        // Fill amount and latest expiration date
1✔
563
        for _, dbCommitment := range dbCommitments {
3✔
564
                dbMergedCommitment.Amount += dbCommitment.Amount
2✔
565
                if dbCommitment.ExpiresAt.After(dbMergedCommitment.ExpiresAt) {
4✔
566
                        dbMergedCommitment.ExpiresAt = dbCommitment.ExpiresAt
2✔
567
                        dbMergedCommitment.Duration = dbCommitment.Duration
2✔
568
                }
2✔
569
        }
570

571
        // Fill workflow context
572
        creationContext := db.CommitmentWorkflowContext{
1✔
573
                Reason:                 db.CommitmentReasonMerge,
1✔
574
                RelatedCommitmentIDs:   commitmentIDs,
1✔
575
                RelatedCommitmentUUIDs: commitmentUUIDs,
1✔
576
        }
1✔
577
        buf, err := json.Marshal(creationContext)
1✔
578
        if respondwith.ErrorText(w, err) {
1✔
579
                return
×
580
        }
×
581
        dbMergedCommitment.CreationContextJSON = json.RawMessage(buf)
1✔
582

1✔
583
        // Insert into database
1✔
584
        err = tx.Insert(&dbMergedCommitment)
1✔
585
        if respondwith.ErrorText(w, err) {
1✔
586
                return
×
587
        }
×
588

589
        // Mark merged commits as superseded
590
        supersedeContext := db.CommitmentWorkflowContext{
1✔
591
                Reason:                 db.CommitmentReasonMerge,
1✔
592
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbMergedCommitment.ID},
1✔
593
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbMergedCommitment.UUID},
1✔
594
        }
1✔
595
        buf, err = json.Marshal(supersedeContext)
1✔
596
        if respondwith.ErrorText(w, err) {
1✔
597
                return
×
598
        }
×
599
        for _, dbCommitment := range dbCommitments {
3✔
600
                dbCommitment.SupersededAt = Some(now)
2✔
601
                dbCommitment.SupersedeContextJSON = Some(json.RawMessage(buf))
2✔
602
                dbCommitment.State = db.CommitmentStateSuperseded
2✔
603
                _, err = tx.Update(&dbCommitment)
2✔
604
                if respondwith.ErrorText(w, err) {
2✔
605
                        return
×
606
                }
×
607
        }
608

609
        err = tx.Commit()
1✔
610
        if respondwith.ErrorText(w, err) {
1✔
611
                return
×
612
        }
×
613

614
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
1✔
615
        if respondwith.ErrorText(w, err) {
1✔
616
                return
×
617
        }
×
618
        serviceInfo, ok := maybeServiceInfo.Unpack()
1✔
619
        if !ok {
1✔
620
                http.Error(w, "service not found", http.StatusNotFound)
×
621
                return
×
622
        }
×
623
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
1✔
624

1✔
625
        c := p.convertCommitmentToDisplayForm(dbMergedCommitment, loc, token, resourceInfo.Unit)
1✔
626
        auditEvent := commitmentEventTarget{
1✔
627
                DomainID:        dbDomain.UUID,
1✔
628
                DomainName:      dbDomain.Name,
1✔
629
                ProjectID:       dbProject.UUID,
1✔
630
                ProjectName:     dbProject.Name,
1✔
631
                Commitments:     []limesresources.Commitment{c},
1✔
632
                WorkflowContext: Some(creationContext),
1✔
633
        }
1✔
634
        p.auditor.Record(audittools.Event{
1✔
635
                Time:       p.timeNow(),
1✔
636
                Request:    r,
1✔
637
                User:       token,
1✔
638
                ReasonCode: http.StatusAccepted,
1✔
639
                Action:     cadf.UpdateAction,
1✔
640
                Target:     auditEvent,
1✔
641
        })
1✔
642

1✔
643
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
644
}
645

646
// As per the API spec, commitments can be renewed 90 days in advance at the earliest.
647
const commitmentRenewalPeriod = 90 * 24 * time.Hour
648

649
// RenewProjectCommitments handles POST /v1/domains/:domain_id/projects/:project_id/commitments/:id/renew.
650
func (p *v1Provider) RenewProjectCommitments(w http.ResponseWriter, r *http.Request) {
6✔
651
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id/renew")
6✔
652
        token := p.CheckToken(r)
6✔
653
        if !token.Require(w, "project:edit") {
6✔
654
                return
×
655
        }
×
656
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
657
        if dbDomain == nil {
6✔
658
                return
×
659
        }
×
660
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
661
        if dbProject == nil {
6✔
662
                return
×
663
        }
×
664

665
        // Load commitment
666
        var dbCommitment db.ProjectCommitmentV2
6✔
667
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
6✔
668
        if errors.Is(err, sql.ErrNoRows) {
6✔
669
                http.Error(w, "no such commitment", http.StatusNotFound)
×
670
                return
×
671
        } else if respondwith.ErrorText(w, err) {
6✔
672
                return
×
673
        }
×
674
        now := p.timeNow()
6✔
675

6✔
676
        // Check if commitment can be renewed
6✔
677
        var errs errext.ErrorSet
6✔
678
        if dbCommitment.State != db.CommitmentStateActive {
7✔
679
                errs.Addf("invalid state %q", dbCommitment.State)
1✔
680
        } else if now.After(dbCommitment.ExpiresAt) {
7✔
681
                errs.Addf("invalid state %q", db.CommitmentStateExpired)
1✔
682
        }
1✔
683
        if now.Before(dbCommitment.ExpiresAt.Add(-commitmentRenewalPeriod)) {
7✔
684
                errs.Addf("renewal attempt too early")
1✔
685
        }
1✔
686
        if dbCommitment.RenewContextJSON.IsSome() {
7✔
687
                errs.Addf("already renewed")
1✔
688
        }
1✔
689

690
        if !errs.IsEmpty() {
10✔
691
                msg := "cannot renew this commitment: " + errs.Join(", ")
4✔
692
                http.Error(w, msg, http.StatusConflict)
4✔
693
                return
4✔
694
        }
4✔
695

696
        // Create renewed commitment
697
        tx, err := p.DB.Begin()
2✔
698
        if respondwith.ErrorText(w, err) {
2✔
699
                return
×
700
        }
×
701
        defer sqlext.RollbackUnlessCommitted(tx)
2✔
702

2✔
703
        var loc core.AZResourceLocation
2✔
704
        err = p.DB.QueryRow(findClusterAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
2✔
705
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
2✔
706
        if errors.Is(err, sql.ErrNoRows) {
2✔
707
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
708
                return
×
709
        } else if respondwith.ErrorText(w, err) {
2✔
710
                return
×
711
        }
×
712

713
        creationContext := db.CommitmentWorkflowContext{
2✔
714
                Reason:                 db.CommitmentReasonRenew,
2✔
715
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
2✔
716
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
2✔
717
        }
2✔
718
        buf, err := json.Marshal(creationContext)
2✔
719
        if respondwith.ErrorText(w, err) {
2✔
720
                return
×
721
        }
×
722
        dbRenewedCommitment := db.ProjectCommitmentV2{
2✔
723
                UUID:                p.generateProjectCommitmentUUID(),
2✔
724
                ProjectID:           dbProject.ID,
2✔
725
                AZResourceID:        dbCommitment.AZResourceID,
2✔
726
                Amount:              dbCommitment.Amount,
2✔
727
                Duration:            dbCommitment.Duration,
2✔
728
                CreatedAt:           now,
2✔
729
                CreatorUUID:         token.UserUUID(),
2✔
730
                CreatorName:         fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
2✔
731
                ConfirmBy:           Some(dbCommitment.ExpiresAt),
2✔
732
                ExpiresAt:           dbCommitment.Duration.AddTo(dbCommitment.ExpiresAt),
2✔
733
                State:               db.CommitmentStatePlanned,
2✔
734
                CreationContextJSON: json.RawMessage(buf),
2✔
735
        }
2✔
736

2✔
737
        err = tx.Insert(&dbRenewedCommitment)
2✔
738
        if respondwith.ErrorText(w, err) {
2✔
739
                return
×
740
        }
×
741

742
        renewContext := db.CommitmentWorkflowContext{
2✔
743
                Reason:                 db.CommitmentReasonRenew,
2✔
744
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbRenewedCommitment.ID},
2✔
745
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbRenewedCommitment.UUID},
2✔
746
        }
2✔
747
        buf, err = json.Marshal(renewContext)
2✔
748
        if respondwith.ErrorText(w, err) {
2✔
749
                return
×
750
        }
×
751
        dbCommitment.RenewContextJSON = Some(json.RawMessage(buf))
2✔
752
        _, err = tx.Update(&dbCommitment)
2✔
753
        if respondwith.ErrorText(w, err) {
2✔
754
                return
×
755
        }
×
756

757
        err = tx.Commit()
2✔
758
        if respondwith.ErrorText(w, err) {
2✔
759
                return
×
760
        }
×
761

762
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
2✔
763
        if respondwith.ErrorText(w, err) {
2✔
764
                return
×
765
        }
×
766
        serviceInfo, ok := maybeServiceInfo.Unpack()
2✔
767
        if !ok {
2✔
768
                http.Error(w, "service not found", http.StatusNotFound)
×
769
                return
×
770
        }
×
771
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
2✔
772

2✔
773
        // Create resultset and auditlogs
2✔
774
        c := p.convertCommitmentToDisplayForm(dbRenewedCommitment, loc, token, resourceInfo.Unit)
2✔
775
        auditEvent := commitmentEventTarget{
2✔
776
                DomainID:        dbDomain.UUID,
2✔
777
                DomainName:      dbDomain.Name,
2✔
778
                ProjectID:       dbProject.UUID,
2✔
779
                ProjectName:     dbProject.Name,
2✔
780
                Commitments:     []limesresources.Commitment{c},
2✔
781
                WorkflowContext: Some(creationContext),
2✔
782
        }
2✔
783

2✔
784
        p.auditor.Record(audittools.Event{
2✔
785
                Time:       p.timeNow(),
2✔
786
                Request:    r,
2✔
787
                User:       token,
2✔
788
                ReasonCode: http.StatusAccepted,
2✔
789
                Action:     cadf.UpdateAction,
2✔
790
                Target:     auditEvent,
2✔
791
        })
2✔
792

2✔
793
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
794
}
795

796
// DeleteProjectCommitment handles DELETE /v1/domains/:domain_id/projects/:project_id/commitments/:id.
797
func (p *v1Provider) DeleteProjectCommitment(w http.ResponseWriter, r *http.Request) {
8✔
798
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id")
8✔
799
        token := p.CheckToken(r)
8✔
800
        if !token.Require(w, "project:edit") { // NOTE: There is a more specific AuthZ check further down below.
8✔
801
                return
×
802
        }
×
803
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
804
        if dbDomain == nil {
9✔
805
                return
1✔
806
        }
1✔
807
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
7✔
808
        if dbProject == nil {
8✔
809
                return
1✔
810
        }
1✔
811

812
        // load commitment
813
        var dbCommitment db.ProjectCommitmentV2
6✔
814
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
6✔
815
        if errors.Is(err, sql.ErrNoRows) {
7✔
816
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
817
                return
1✔
818
        } else if respondwith.ErrorText(w, err) {
6✔
819
                return
×
820
        }
×
821
        var loc core.AZResourceLocation
5✔
822
        err = p.DB.QueryRow(findClusterAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
5✔
823
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
5✔
824
        if errors.Is(err, sql.ErrNoRows) {
5✔
825
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
826
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
827
                return
×
828
        } else if respondwith.ErrorText(w, err) {
5✔
829
                return
×
830
        }
×
831

832
        // check authorization for this specific commitment
833
        if !p.canDeleteCommitment(token, dbCommitment) {
6✔
834
                http.Error(w, "Forbidden", http.StatusForbidden)
1✔
835
                return
1✔
836
        }
1✔
837

838
        // perform deletion
839
        _, err = p.DB.Delete(&dbCommitment)
4✔
840
        if respondwith.ErrorText(w, err) {
4✔
841
                return
×
842
        }
×
843
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
4✔
844
        if respondwith.ErrorText(w, err) {
4✔
845
                return
×
846
        }
×
847
        serviceInfo, ok := maybeServiceInfo.Unpack()
4✔
848
        if !ok {
4✔
849
                http.Error(w, "service not found", http.StatusNotFound)
×
850
                return
×
851
        }
×
852
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
4✔
853
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
4✔
854
        p.auditor.Record(audittools.Event{
4✔
855
                Time:       p.timeNow(),
4✔
856
                Request:    r,
4✔
857
                User:       token,
4✔
858
                ReasonCode: http.StatusNoContent,
4✔
859
                Action:     cadf.DeleteAction,
4✔
860
                Target: commitmentEventTarget{
4✔
861
                        DomainID:    dbDomain.UUID,
4✔
862
                        DomainName:  dbDomain.Name,
4✔
863
                        ProjectID:   dbProject.UUID,
4✔
864
                        ProjectName: dbProject.Name,
4✔
865
                        Commitments: []limesresources.Commitment{c},
4✔
866
                },
4✔
867
        })
4✔
868

4✔
869
        w.WriteHeader(http.StatusNoContent)
4✔
870
}
871

872
func (p *v1Provider) canDeleteCommitment(token *gopherpolicy.Token, commitment db.ProjectCommitmentV2) bool {
64✔
873
        // up to 24 hours after creation of fresh commitments, future commitments can still be deleted by their creators
64✔
874
        if commitment.State == db.CommitmentStatePlanned || commitment.State == db.CommitmentStatePending || commitment.State == db.CommitmentStateActive {
128✔
875
                var creationContext db.CommitmentWorkflowContext
64✔
876
                err := json.Unmarshal(commitment.CreationContextJSON, &creationContext)
64✔
877
                if err == nil && creationContext.Reason == db.CommitmentReasonCreate && p.timeNow().Before(commitment.CreatedAt.Add(24*time.Hour)) {
104✔
878
                        if token.Check("project:edit") {
80✔
879
                                return true
40✔
880
                        }
40✔
881
                }
882
        }
883

884
        // afterwards, a more specific permission is required to delete it
885
        //
886
        // This protects cloud admins making capacity planning decisions based on future commitments
887
        // from having their forecasts ruined by project admins suffering from buyer's remorse.
888
        return token.Check("project:uncommit")
24✔
889
}
890

891
// StartCommitmentTransfer handles POST /v1/domains/:id/projects/:id/commitments/:id/start-transfer
892
func (p *v1Provider) StartCommitmentTransfer(w http.ResponseWriter, r *http.Request) {
8✔
893
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id/start-transfer")
8✔
894
        token := p.CheckToken(r)
8✔
895
        if !token.Require(w, "project:edit") {
8✔
896
                return
×
897
        }
×
898
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
899
        if dbDomain == nil {
8✔
900
                return
×
901
        }
×
902
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
8✔
903
        if dbProject == nil {
8✔
904
                return
×
905
        }
×
906
        // TODO: eventually migrate this struct into go-api-declarations
907
        var parseTarget struct {
8✔
908
                Request struct {
8✔
909
                        Amount         uint64                                  `json:"amount"`
8✔
910
                        TransferStatus limesresources.CommitmentTransferStatus `json:"transfer_status,omitempty"`
8✔
911
                } `json:"commitment"`
8✔
912
        }
8✔
913
        if !RequireJSON(w, r, &parseTarget) {
8✔
914
                return
×
915
        }
×
916
        req := parseTarget.Request
8✔
917

8✔
918
        if req.TransferStatus != limesresources.CommitmentTransferStatusUnlisted && req.TransferStatus != limesresources.CommitmentTransferStatusPublic {
8✔
919
                http.Error(w, fmt.Sprintf("Invalid transfer_status code. Must be %s or %s.", limesresources.CommitmentTransferStatusUnlisted, limesresources.CommitmentTransferStatusPublic), http.StatusBadRequest)
×
920
                return
×
921
        }
×
922

923
        if req.Amount <= 0 {
9✔
924
                http.Error(w, "delivered amount needs to be a positive value.", http.StatusBadRequest)
1✔
925
                return
1✔
926
        }
1✔
927

928
        // load commitment
929
        var dbCommitment db.ProjectCommitmentV2
7✔
930
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
7✔
931
        if errors.Is(err, sql.ErrNoRows) {
7✔
932
                http.Error(w, "no such commitment", http.StatusNotFound)
×
933
                return
×
934
        } else if respondwith.ErrorText(w, err) {
7✔
935
                return
×
936
        }
×
937

938
        // Mark whole commitment or a newly created, splitted one as transferrable.
939
        tx, err := p.DB.Begin()
7✔
940
        if respondwith.ErrorText(w, err) {
7✔
941
                return
×
942
        }
×
943
        defer sqlext.RollbackUnlessCommitted(tx)
7✔
944
        transferToken := p.generateTransferToken()
7✔
945

7✔
946
        // Deny requests with a greater amount than the commitment.
7✔
947
        if req.Amount > dbCommitment.Amount {
8✔
948
                http.Error(w, "delivered amount exceeds the commitment amount.", http.StatusBadRequest)
1✔
949
                return
1✔
950
        }
1✔
951

952
        if req.Amount == dbCommitment.Amount {
10✔
953
                dbCommitment.TransferStatus = req.TransferStatus
4✔
954
                dbCommitment.TransferToken = Some(transferToken)
4✔
955
                _, err = tx.Update(&dbCommitment)
4✔
956
                if respondwith.ErrorText(w, err) {
4✔
957
                        return
×
958
                }
×
959
        } else {
2✔
960
                now := p.timeNow()
2✔
961
                transferAmount := req.Amount
2✔
962
                remainingAmount := dbCommitment.Amount - req.Amount
2✔
963
                transferCommitment, err := p.buildSplitCommitment(dbCommitment, transferAmount)
2✔
964
                if respondwith.ErrorText(w, err) {
2✔
965
                        return
×
966
                }
×
967
                transferCommitment.TransferStatus = req.TransferStatus
2✔
968
                transferCommitment.TransferToken = Some(transferToken)
2✔
969
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
2✔
970
                if respondwith.ErrorText(w, err) {
2✔
971
                        return
×
972
                }
×
973
                err = tx.Insert(&transferCommitment)
2✔
974
                if respondwith.ErrorText(w, err) {
2✔
975
                        return
×
976
                }
×
977
                err = tx.Insert(&remainingCommitment)
2✔
978
                if respondwith.ErrorText(w, err) {
2✔
979
                        return
×
980
                }
×
981
                supersedeContext := db.CommitmentWorkflowContext{
2✔
982
                        Reason:                 db.CommitmentReasonSplit,
2✔
983
                        RelatedCommitmentIDs:   []db.ProjectCommitmentID{transferCommitment.ID, remainingCommitment.ID},
2✔
984
                        RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{transferCommitment.UUID, remainingCommitment.UUID},
2✔
985
                }
2✔
986
                buf, err := json.Marshal(supersedeContext)
2✔
987
                if respondwith.ErrorText(w, err) {
2✔
988
                        return
×
989
                }
×
990
                dbCommitment.State = db.CommitmentStateSuperseded
2✔
991
                dbCommitment.SupersededAt = Some(now)
2✔
992
                dbCommitment.SupersedeContextJSON = Some(json.RawMessage(buf))
2✔
993
                _, err = tx.Update(&dbCommitment)
2✔
994
                if respondwith.ErrorText(w, err) {
2✔
995
                        return
×
996
                }
×
997
                dbCommitment = transferCommitment
2✔
998
        }
999
        err = tx.Commit()
6✔
1000
        if respondwith.ErrorText(w, err) {
6✔
1001
                return
×
1002
        }
×
1003

1004
        var loc core.AZResourceLocation
6✔
1005
        err = p.DB.QueryRow(findClusterAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
6✔
1006
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
6✔
1007
        if errors.Is(err, sql.ErrNoRows) {
6✔
1008
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1009
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1010
                return
×
1011
        } else if respondwith.ErrorText(w, err) {
6✔
1012
                return
×
1013
        }
×
1014

1015
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
6✔
1016
        if respondwith.ErrorText(w, err) {
6✔
1017
                return
×
1018
        }
×
1019
        serviceInfo, ok := maybeServiceInfo.Unpack()
6✔
1020
        if !ok {
6✔
1021
                http.Error(w, "service not found", http.StatusNotFound)
×
1022
                return
×
1023
        }
×
1024
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
6✔
1025
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
6✔
1026
        if respondwith.ErrorText(w, err) {
6✔
1027
                return
×
1028
        }
×
1029
        p.auditor.Record(audittools.Event{
6✔
1030
                Time:       p.timeNow(),
6✔
1031
                Request:    r,
6✔
1032
                User:       token,
6✔
1033
                ReasonCode: http.StatusAccepted,
6✔
1034
                Action:     cadf.UpdateAction,
6✔
1035
                Target: commitmentEventTarget{
6✔
1036
                        DomainID:    dbDomain.UUID,
6✔
1037
                        DomainName:  dbDomain.Name,
6✔
1038
                        ProjectID:   dbProject.UUID,
6✔
1039
                        ProjectName: dbProject.Name,
6✔
1040
                        Commitments: []limesresources.Commitment{c},
6✔
1041
                },
6✔
1042
        })
6✔
1043
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
6✔
1044
}
1045

1046
func (p *v1Provider) buildSplitCommitment(dbCommitment db.ProjectCommitmentV2, amount uint64) (db.ProjectCommitmentV2, error) {
5✔
1047
        now := p.timeNow()
5✔
1048
        creationContext := db.CommitmentWorkflowContext{
5✔
1049
                Reason:                 db.CommitmentReasonSplit,
5✔
1050
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
5✔
1051
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
5✔
1052
        }
5✔
1053
        buf, err := json.Marshal(creationContext)
5✔
1054
        if err != nil {
5✔
NEW
1055
                return db.ProjectCommitmentV2{}, err
×
1056
        }
×
1057
        return db.ProjectCommitmentV2{
5✔
1058
                UUID:                p.generateProjectCommitmentUUID(),
5✔
1059
                ProjectID:           dbCommitment.ProjectID,
5✔
1060
                AZResourceID:        dbCommitment.AZResourceID,
5✔
1061
                Amount:              amount,
5✔
1062
                Duration:            dbCommitment.Duration,
5✔
1063
                CreatedAt:           now,
5✔
1064
                CreatorUUID:         dbCommitment.CreatorUUID,
5✔
1065
                CreatorName:         dbCommitment.CreatorName,
5✔
1066
                ConfirmBy:           dbCommitment.ConfirmBy,
5✔
1067
                ConfirmedAt:         dbCommitment.ConfirmedAt,
5✔
1068
                ExpiresAt:           dbCommitment.ExpiresAt,
5✔
1069
                CreationContextJSON: json.RawMessage(buf),
5✔
1070
                State:               dbCommitment.State,
5✔
1071
        }, nil
5✔
1072
}
1073

1074
func (p *v1Provider) buildConvertedCommitment(dbCommitment db.ProjectCommitmentV2, azResourceID db.ClusterAZResourceID, amount uint64) (db.ProjectCommitmentV2, error) {
2✔
1075
        now := p.timeNow()
2✔
1076
        creationContext := db.CommitmentWorkflowContext{
2✔
1077
                Reason:                 db.CommitmentReasonConvert,
2✔
1078
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1079
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
2✔
1080
        }
2✔
1081
        buf, err := json.Marshal(creationContext)
2✔
1082
        if err != nil {
2✔
NEW
1083
                return db.ProjectCommitmentV2{}, err
×
1084
        }
×
1085
        return db.ProjectCommitmentV2{
2✔
1086
                UUID:                p.generateProjectCommitmentUUID(),
2✔
1087
                ProjectID:           dbCommitment.ProjectID,
2✔
1088
                AZResourceID:        azResourceID,
2✔
1089
                Amount:              amount,
2✔
1090
                Duration:            dbCommitment.Duration,
2✔
1091
                CreatedAt:           now,
2✔
1092
                CreatorUUID:         dbCommitment.CreatorUUID,
2✔
1093
                CreatorName:         dbCommitment.CreatorName,
2✔
1094
                ConfirmBy:           dbCommitment.ConfirmBy,
2✔
1095
                ConfirmedAt:         dbCommitment.ConfirmedAt,
2✔
1096
                ExpiresAt:           dbCommitment.ExpiresAt,
2✔
1097
                CreationContextJSON: json.RawMessage(buf),
2✔
1098
                State:               dbCommitment.State,
2✔
1099
        }, nil
2✔
1100
}
1101

1102
// GetCommitmentByTransferToken handles GET /v1/commitments/{token}
1103
func (p *v1Provider) GetCommitmentByTransferToken(w http.ResponseWriter, r *http.Request) {
2✔
1104
        httpapi.IdentifyEndpoint(r, "/v1/commitments/:token")
2✔
1105
        token := p.CheckToken(r)
2✔
1106
        if !token.Require(w, "cluster:show_basic") {
2✔
1107
                return
×
1108
        }
×
1109
        transferToken := mux.Vars(r)["token"]
2✔
1110

2✔
1111
        // The token column is a unique key, so we expect only one result.
2✔
1112
        var dbCommitment db.ProjectCommitmentV2
2✔
1113
        err := p.DB.SelectOne(&dbCommitment, findCommitmentByTransferToken, transferToken)
2✔
1114
        if errors.Is(err, sql.ErrNoRows) {
3✔
1115
                http.Error(w, "no matching commitment found.", http.StatusNotFound)
1✔
1116
                return
1✔
1117
        } else if respondwith.ErrorText(w, err) {
2✔
1118
                return
×
1119
        }
×
1120

1121
        var loc core.AZResourceLocation
1✔
1122
        err = p.DB.QueryRow(findClusterAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
1✔
1123
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
1✔
1124
        if errors.Is(err, sql.ErrNoRows) {
1✔
1125
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1126
                http.Error(w, "location data not found.", http.StatusNotFound)
×
1127
                return
×
1128
        } else if respondwith.ErrorText(w, err) {
1✔
1129
                return
×
1130
        }
×
1131

1132
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
1✔
1133
        if respondwith.ErrorText(w, err) {
1✔
1134
                return
×
1135
        }
×
1136
        serviceInfo, ok := maybeServiceInfo.Unpack()
1✔
1137
        if !ok {
1✔
1138
                http.Error(w, "service not found", http.StatusNotFound)
×
1139
                return
×
1140
        }
×
1141
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
1✔
1142
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
1✔
1143
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
1144
}
1145

1146
// TransferCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/transfer-commitment/{id}?token={token}
1147
func (p *v1Provider) TransferCommitment(w http.ResponseWriter, r *http.Request) {
5✔
1148
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/transfer-commitment/:id")
5✔
1149
        token := p.CheckToken(r)
5✔
1150
        if !token.Require(w, "project:edit") {
5✔
1151
                return
×
1152
        }
×
1153
        transferToken := r.Header.Get("Transfer-Token")
5✔
1154
        if transferToken == "" {
6✔
1155
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
1✔
1156
                return
1✔
1157
        }
1✔
1158
        commitmentID := mux.Vars(r)["id"]
4✔
1159
        if commitmentID == "" {
4✔
1160
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1161
                return
×
1162
        }
×
1163
        dbDomain := p.FindDomainFromRequest(w, r)
4✔
1164
        if dbDomain == nil {
4✔
1165
                return
×
1166
        }
×
1167
        targetProject := p.FindProjectFromRequest(w, r, dbDomain)
4✔
1168
        if targetProject == nil {
4✔
1169
                return
×
1170
        }
×
1171

1172
        // find commitment by transfer_token
1173
        var dbCommitment db.ProjectCommitmentV2
4✔
1174
        err := p.DB.SelectOne(&dbCommitment, getCommitmentWithMatchingTransferTokenQuery, commitmentID, transferToken)
4✔
1175
        if errors.Is(err, sql.ErrNoRows) {
5✔
1176
                http.Error(w, "no matching commitment found", http.StatusNotFound)
1✔
1177
                return
1✔
1178
        } else if respondwith.ErrorText(w, err) {
4✔
1179
                return
×
1180
        }
×
1181

1182
        var loc core.AZResourceLocation
3✔
1183
        err = p.DB.QueryRow(findClusterAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
3✔
1184
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
3✔
1185
        if errors.Is(err, sql.ErrNoRows) {
3✔
1186
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1187
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1188
                return
×
1189
        } else if respondwith.ErrorText(w, err) {
3✔
1190
                return
×
1191
        }
×
1192

1193
        // get target service and AZ resource
1194
        var (
3✔
1195
                sourceResourceID db.ProjectResourceID
3✔
1196
                targetResourceID db.ProjectResourceID
3✔
1197
        )
3✔
1198
        err = p.DB.QueryRow(findTargetProjectResourceBySourceIDQuery, dbCommitment.ID, targetProject.ID).
3✔
1199
                Scan(&sourceResourceID, &targetResourceID)
3✔
1200
        if respondwith.ErrorText(w, err) {
3✔
1201
                return
×
1202
        }
×
1203

1204
        // validate that we have enough committable capacity on the receiving side
1205
        tx, err := p.DB.Begin()
3✔
1206
        if respondwith.ErrorText(w, err) {
3✔
1207
                return
×
1208
        }
×
1209
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1210
        ok, err := datamodel.CanMoveExistingCommitment(dbCommitment.Amount, loc, sourceResourceID, targetResourceID, p.Cluster, tx)
3✔
1211
        if respondwith.ErrorText(w, err) {
3✔
1212
                return
×
1213
        }
×
1214
        if !ok {
4✔
1215
                http.Error(w, "not enough committable capacity on the receiving side", http.StatusConflict)
1✔
1216
                return
1✔
1217
        }
1✔
1218

1219
        dbCommitment.TransferStatus = ""
2✔
1220
        dbCommitment.TransferToken = None[string]()
2✔
1221
        dbCommitment.ProjectID = targetProject.ID
2✔
1222
        _, err = tx.Update(&dbCommitment)
2✔
1223
        if respondwith.ErrorText(w, err) {
2✔
1224
                return
×
1225
        }
×
1226
        err = tx.Commit()
2✔
1227
        if respondwith.ErrorText(w, err) {
2✔
1228
                return
×
1229
        }
×
1230

1231
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
2✔
1232
        if respondwith.ErrorText(w, err) {
2✔
1233
                return
×
1234
        }
×
1235
        serviceInfo, ok := maybeServiceInfo.Unpack()
2✔
1236
        if !ok {
2✔
1237
                http.Error(w, "service not found", http.StatusNotFound)
×
1238
                return
×
1239
        }
×
1240
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
2✔
1241
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
2✔
1242
        p.auditor.Record(audittools.Event{
2✔
1243
                Time:       p.timeNow(),
2✔
1244
                Request:    r,
2✔
1245
                User:       token,
2✔
1246
                ReasonCode: http.StatusAccepted,
2✔
1247
                Action:     cadf.UpdateAction,
2✔
1248
                Target: commitmentEventTarget{
2✔
1249
                        DomainID:    dbDomain.UUID,
2✔
1250
                        DomainName:  dbDomain.Name,
2✔
1251
                        ProjectID:   targetProject.UUID,
2✔
1252
                        ProjectName: targetProject.Name,
2✔
1253
                        Commitments: []limesresources.Commitment{c},
2✔
1254
                },
2✔
1255
        })
2✔
1256

2✔
1257
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1258
}
1259

1260
// GetCommitmentConversion handles GET /v1/commitment-conversion/{service_type}/{resource_name}
1261
func (p *v1Provider) GetCommitmentConversions(w http.ResponseWriter, r *http.Request) {
2✔
1262
        httpapi.IdentifyEndpoint(r, "/v1/commitment-conversion/:service_type/:resource_name")
2✔
1263
        token := p.CheckToken(r)
2✔
1264
        if !token.Require(w, "cluster:show_basic") {
2✔
1265
                return
×
1266
        }
×
1267

1268
        // TODO v2 API: This endpoint should be project-scoped in order to make it
1269
        // easier to select the correct domain scope for the CommitmentBehavior.
1270
        forTokenScope := func(behavior core.CommitmentBehavior) core.ScopedCommitmentBehavior {
13✔
1271
                name := cmp.Or(token.ProjectScopeDomainName(), token.DomainScopeName(), "")
11✔
1272
                if name != "" {
22✔
1273
                        return behavior.ForDomain(name)
11✔
1274
                }
11✔
1275
                return behavior.ForCluster()
×
1276
        }
1277

1278
        // validate request
1279
        vars := mux.Vars(r)
2✔
1280
        serviceInfos, err := p.Cluster.AllServiceInfos()
2✔
1281
        if respondwith.ErrorText(w, err) {
2✔
1282
                return
×
1283
        }
×
1284

1285
        nm := core.BuildResourceNameMapping(p.Cluster, serviceInfos)
2✔
1286
        sourceServiceType, sourceResourceName, exists := nm.MapFromV1API(
2✔
1287
                limes.ServiceType(vars["service_type"]),
2✔
1288
                limesresources.ResourceName(vars["resource_name"]),
2✔
1289
        )
2✔
1290
        if !exists {
2✔
1291
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", vars["service_type"], vars["resource_name"])
×
1292
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1293
                return
×
1294
        }
×
1295
        sourceBehavior := forTokenScope(p.Cluster.CommitmentBehaviorForResource(sourceServiceType, sourceResourceName))
2✔
1296

2✔
1297
        serviceInfo := core.InfoForService(serviceInfos, sourceServiceType)
2✔
1298
        sourceResInfo := core.InfoForResource(serviceInfo, sourceResourceName)
2✔
1299

2✔
1300
        // enumerate possible conversions
2✔
1301
        conversions := make([]limesresources.CommitmentConversionRule, 0)
2✔
1302
        if sourceBehavior.ConversionRule.IsSome() {
4✔
1303
                for _, targetServiceType := range slices.Sorted(maps.Keys(serviceInfos)) {
8✔
1304
                        for targetResourceName, targetResInfo := range serviceInfos[targetServiceType].Resources {
28✔
1305
                                if sourceServiceType == targetServiceType && sourceResourceName == targetResourceName {
24✔
1306
                                        continue
2✔
1307
                                }
1308
                                if sourceResInfo.Unit != targetResInfo.Unit {
31✔
1309
                                        continue
11✔
1310
                                }
1311

1312
                                targetBehavior := forTokenScope(p.Cluster.CommitmentBehaviorForResource(targetServiceType, targetResourceName))
9✔
1313
                                if rate, ok := sourceBehavior.GetConversionRateTo(targetBehavior).Unpack(); ok {
13✔
1314
                                        apiServiceType, apiResourceName, ok := nm.MapToV1API(targetServiceType, targetResourceName)
4✔
1315
                                        if ok {
8✔
1316
                                                conversions = append(conversions, limesresources.CommitmentConversionRule{
4✔
1317
                                                        FromAmount:     rate.FromAmount,
4✔
1318
                                                        ToAmount:       rate.ToAmount,
4✔
1319
                                                        TargetService:  apiServiceType,
4✔
1320
                                                        TargetResource: apiResourceName,
4✔
1321
                                                })
4✔
1322
                                        }
4✔
1323
                                }
1324
                        }
1325
                }
1326
        }
1327

1328
        // use a defined sorting to ensure deterministic behavior in tests
1329
        slices.SortFunc(conversions, func(lhs, rhs limesresources.CommitmentConversionRule) int {
5✔
1330
                result := strings.Compare(string(lhs.TargetService), string(rhs.TargetService))
3✔
1331
                if result != 0 {
5✔
1332
                        return result
2✔
1333
                }
2✔
1334
                return strings.Compare(string(lhs.TargetResource), string(rhs.TargetResource))
1✔
1335
        })
1336

1337
        respondwith.JSON(w, http.StatusOK, map[string]any{"conversions": conversions})
2✔
1338
}
1339

1340
// ConvertCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/convert
1341
func (p *v1Provider) ConvertCommitment(w http.ResponseWriter, r *http.Request) {
9✔
1342
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/convert")
9✔
1343
        token := p.CheckToken(r)
9✔
1344
        if !token.Require(w, "project:edit") {
9✔
1345
                return
×
1346
        }
×
1347
        commitmentID := mux.Vars(r)["commitment_id"]
9✔
1348
        if commitmentID == "" {
9✔
1349
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1350
                return
×
1351
        }
×
1352
        dbDomain := p.FindDomainFromRequest(w, r)
9✔
1353
        if dbDomain == nil {
9✔
1354
                return
×
1355
        }
×
1356
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
9✔
1357
        if dbProject == nil {
9✔
1358
                return
×
1359
        }
×
1360

1361
        // section: sourceBehavior
1362
        var dbCommitment db.ProjectCommitmentV2
9✔
1363
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
9✔
1364
        if errors.Is(err, sql.ErrNoRows) {
10✔
1365
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
1366
                return
1✔
1367
        } else if respondwith.ErrorText(w, err) {
9✔
1368
                return
×
1369
        }
×
1370
        var sourceLoc core.AZResourceLocation
8✔
1371
        err = p.DB.QueryRow(findClusterAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
8✔
1372
                Scan(&sourceLoc.ServiceType, &sourceLoc.ResourceName, &sourceLoc.AvailabilityZone)
8✔
1373
        if errors.Is(err, sql.ErrNoRows) {
8✔
1374
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1375
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1376
                return
×
1377
        } else if respondwith.ErrorText(w, err) {
8✔
1378
                return
×
1379
        }
×
1380
        sourceBehavior := p.Cluster.CommitmentBehaviorForResource(sourceLoc.ServiceType, sourceLoc.ResourceName).ForDomain(dbDomain.Name)
8✔
1381

8✔
1382
        // section: targetBehavior
8✔
1383
        var parseTarget struct {
8✔
1384
                Request struct {
8✔
1385
                        TargetService  limes.ServiceType           `json:"target_service"`
8✔
1386
                        TargetResource limesresources.ResourceName `json:"target_resource"`
8✔
1387
                        SourceAmount   uint64                      `json:"source_amount"`
8✔
1388
                        TargetAmount   uint64                      `json:"target_amount"`
8✔
1389
                } `json:"commitment"`
8✔
1390
        }
8✔
1391
        if !RequireJSON(w, r, &parseTarget) {
8✔
1392
                return
×
1393
        }
×
1394
        req := parseTarget.Request
8✔
1395
        serviceInfos, err := p.Cluster.AllServiceInfos()
8✔
1396
        if respondwith.ErrorText(w, err) {
8✔
1397
                return
×
1398
        }
×
1399
        nm := core.BuildResourceNameMapping(p.Cluster, serviceInfos)
8✔
1400
        targetServiceType, targetResourceName, exists := nm.MapFromV1API(req.TargetService, req.TargetResource)
8✔
1401
        if !exists {
8✔
1402
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", req.TargetService, req.TargetResource)
×
1403
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1404
                return
×
1405
        }
×
1406
        targetBehavior := p.Cluster.CommitmentBehaviorForResource(targetServiceType, targetResourceName).ForDomain(dbDomain.Name)
8✔
1407
        if sourceLoc.ResourceName == targetResourceName && sourceLoc.ServiceType == targetServiceType {
9✔
1408
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
1✔
1409
                return
1✔
1410
        }
1✔
1411
        if len(targetBehavior.Durations) == 0 {
7✔
1412
                msg := fmt.Sprintf("commitments are not enabled for resource %s/%s", req.TargetService, req.TargetResource)
×
1413
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1414
                return
×
1415
        }
×
1416
        rate, ok := sourceBehavior.GetConversionRateTo(targetBehavior).Unpack()
7✔
1417
        if !ok {
8✔
1418
                msg := fmt.Sprintf("commitment is not convertible into resource %s/%s", req.TargetService, req.TargetResource)
1✔
1419
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1420
                return
1✔
1421
        }
1✔
1422

1423
        // section: conversion
1424
        if req.SourceAmount > dbCommitment.Amount {
6✔
1425
                msg := fmt.Sprintf("unprocessable source amount. provided: %v, commitment: %v", req.SourceAmount, dbCommitment.Amount)
×
1426
                http.Error(w, msg, http.StatusConflict)
×
1427
                return
×
1428
        }
×
1429
        conversionAmount := (req.SourceAmount / rate.FromAmount) * rate.ToAmount
6✔
1430
        remainderAmount := req.SourceAmount % rate.FromAmount
6✔
1431
        if remainderAmount > 0 {
8✔
1432
                msg := fmt.Sprintf("amount: %v does not fit into conversion rate of: %v", req.SourceAmount, rate.FromAmount)
2✔
1433
                http.Error(w, msg, http.StatusConflict)
2✔
1434
                return
2✔
1435
        }
2✔
1436
        if conversionAmount != req.TargetAmount {
5✔
1437
                msg := fmt.Sprintf("conversion mismatch. provided: %v, calculated: %v", req.TargetAmount, conversionAmount)
1✔
1438
                http.Error(w, msg, http.StatusConflict)
1✔
1439
                return
1✔
1440
        }
1✔
1441

1442
        tx, err := p.DB.Begin()
3✔
1443
        if respondwith.ErrorText(w, err) {
3✔
1444
                return
×
1445
        }
×
1446
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1447

3✔
1448
        var (
3✔
1449
                targetResourceID   db.ProjectResourceID
3✔
1450
                targetAZResourceID db.ClusterAZResourceID
3✔
1451
        )
3✔
1452
        err = p.DB.QueryRow(findTargetClusterAZResourceByTargetProjectQuery, dbProject.ID, targetServiceType, targetResourceName, sourceLoc.AvailabilityZone).
3✔
1453
                Scan(&targetResourceID, &targetAZResourceID)
3✔
1454
        if respondwith.ErrorText(w, err) {
3✔
1455
                return
×
1456
        }
×
1457
        // defense in depth. ServiceType and ResourceName of source and target are already checked. Here it's possible to explicitly check the ID's.
1458
        if dbCommitment.AZResourceID == targetAZResourceID {
3✔
1459
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
×
1460
                return
×
1461
        }
×
1462
        targetLoc := core.AZResourceLocation{
3✔
1463
                ServiceType:      targetServiceType,
3✔
1464
                ResourceName:     targetResourceName,
3✔
1465
                AvailabilityZone: sourceLoc.AvailabilityZone,
3✔
1466
        }
3✔
1467
        // The commitment at the source resource was already confirmed and checked.
3✔
1468
        // Therefore only the addition to the target resource has to be checked against.
3✔
1469
        if dbCommitment.ConfirmedAt.IsSome() {
5✔
1470
                ok, err := datamodel.CanConfirmNewCommitment(targetLoc, targetResourceID, conversionAmount, p.Cluster, p.DB)
2✔
1471
                if respondwith.ErrorText(w, err) {
2✔
1472
                        return
×
1473
                }
×
1474
                if !ok {
3✔
1475
                        http.Error(w, "not enough capacity to confirm the commitment", http.StatusUnprocessableEntity)
1✔
1476
                        return
1✔
1477
                }
1✔
1478
        }
1479

1480
        auditEvent := commitmentEventTarget{
2✔
1481
                DomainID:    dbDomain.UUID,
2✔
1482
                DomainName:  dbDomain.Name,
2✔
1483
                ProjectID:   dbProject.UUID,
2✔
1484
                ProjectName: dbProject.Name,
2✔
1485
        }
2✔
1486

2✔
1487
        var (
2✔
1488
                relatedCommitmentIDs   []db.ProjectCommitmentID
2✔
1489
                relatedCommitmentUUIDs []db.ProjectCommitmentUUID
2✔
1490
        )
2✔
1491
        remainingAmount := dbCommitment.Amount - req.SourceAmount
2✔
1492
        serviceInfo := core.InfoForService(serviceInfos, sourceLoc.ServiceType)
2✔
1493
        resourceInfo := core.InfoForResource(serviceInfo, sourceLoc.ResourceName)
2✔
1494
        if remainingAmount > 0 {
3✔
1495
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
1✔
1496
                if respondwith.ErrorText(w, err) {
1✔
1497
                        return
×
1498
                }
×
1499
                relatedCommitmentIDs = append(relatedCommitmentIDs, remainingCommitment.ID)
1✔
1500
                relatedCommitmentUUIDs = append(relatedCommitmentUUIDs, remainingCommitment.UUID)
1✔
1501
                err = tx.Insert(&remainingCommitment)
1✔
1502
                if respondwith.ErrorText(w, err) {
1✔
1503
                        return
×
1504
                }
×
1505
                auditEvent.Commitments = append(auditEvent.Commitments,
1✔
1506
                        p.convertCommitmentToDisplayForm(remainingCommitment, sourceLoc, token, resourceInfo.Unit),
1✔
1507
                )
1✔
1508
        }
1509

1510
        convertedCommitment, err := p.buildConvertedCommitment(dbCommitment, targetAZResourceID, conversionAmount)
2✔
1511
        if respondwith.ErrorText(w, err) {
2✔
1512
                return
×
1513
        }
×
1514
        relatedCommitmentIDs = append(relatedCommitmentIDs, convertedCommitment.ID)
2✔
1515
        relatedCommitmentUUIDs = append(relatedCommitmentUUIDs, convertedCommitment.UUID)
2✔
1516
        err = tx.Insert(&convertedCommitment)
2✔
1517
        if respondwith.ErrorText(w, err) {
2✔
1518
                return
×
1519
        }
×
1520

1521
        // supersede the original commitment
1522
        now := p.timeNow()
2✔
1523
        supersedeContext := db.CommitmentWorkflowContext{
2✔
1524
                Reason:                 db.CommitmentReasonConvert,
2✔
1525
                RelatedCommitmentIDs:   relatedCommitmentIDs,
2✔
1526
                RelatedCommitmentUUIDs: relatedCommitmentUUIDs,
2✔
1527
        }
2✔
1528
        buf, err := json.Marshal(supersedeContext)
2✔
1529
        if respondwith.ErrorText(w, err) {
2✔
1530
                return
×
1531
        }
×
1532
        dbCommitment.State = db.CommitmentStateSuperseded
2✔
1533
        dbCommitment.SupersededAt = Some(now)
2✔
1534
        dbCommitment.SupersedeContextJSON = Some(json.RawMessage(buf))
2✔
1535
        _, err = tx.Update(&dbCommitment)
2✔
1536
        if respondwith.ErrorText(w, err) {
2✔
1537
                return
×
1538
        }
×
1539

1540
        err = tx.Commit()
2✔
1541
        if respondwith.ErrorText(w, err) {
2✔
1542
                return
×
1543
        }
×
1544

1545
        c := p.convertCommitmentToDisplayForm(convertedCommitment, targetLoc, token, resourceInfo.Unit)
2✔
1546
        auditEvent.Commitments = append([]limesresources.Commitment{c}, auditEvent.Commitments...)
2✔
1547
        auditEvent.WorkflowContext = Some(db.CommitmentWorkflowContext{
2✔
1548
                Reason:                 db.CommitmentReasonSplit,
2✔
1549
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1550
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
2✔
1551
        })
2✔
1552
        p.auditor.Record(audittools.Event{
2✔
1553
                Time:       p.timeNow(),
2✔
1554
                Request:    r,
2✔
1555
                User:       token,
2✔
1556
                ReasonCode: http.StatusAccepted,
2✔
1557
                Action:     cadf.UpdateAction,
2✔
1558
                Target:     auditEvent,
2✔
1559
        })
2✔
1560

2✔
1561
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1562
}
1563

1564
// ExtendCommitmentDuration handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/update-duration
1565
func (p *v1Provider) UpdateCommitmentDuration(w http.ResponseWriter, r *http.Request) {
6✔
1566
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/update-duration")
6✔
1567
        token := p.CheckToken(r)
6✔
1568
        if !token.Require(w, "project:edit") {
6✔
1569
                return
×
1570
        }
×
1571
        commitmentID := mux.Vars(r)["commitment_id"]
6✔
1572
        if commitmentID == "" {
6✔
1573
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1574
                return
×
1575
        }
×
1576
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
1577
        if dbDomain == nil {
6✔
1578
                return
×
1579
        }
×
1580
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
1581
        if dbProject == nil {
6✔
1582
                return
×
1583
        }
×
1584
        var Request struct {
6✔
1585
                Duration limesresources.CommitmentDuration `json:"duration"`
6✔
1586
        }
6✔
1587
        req := Request
6✔
1588
        if !RequireJSON(w, r, &req) {
6✔
1589
                return
×
1590
        }
×
1591

1592
        var dbCommitment db.ProjectCommitmentV2
6✔
1593
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
6✔
1594
        if errors.Is(err, sql.ErrNoRows) {
6✔
1595
                http.Error(w, "no such commitment", http.StatusNotFound)
×
1596
                return
×
1597
        } else if respondwith.ErrorText(w, err) {
6✔
1598
                return
×
1599
        }
×
1600

1601
        now := p.timeNow()
6✔
1602
        if dbCommitment.ExpiresAt.Before(now) || dbCommitment.ExpiresAt.Equal(now) {
7✔
1603
                http.Error(w, "unable to process expired commitment", http.StatusForbidden)
1✔
1604
                return
1✔
1605
        }
1✔
1606

1607
        if dbCommitment.State == db.CommitmentStateSuperseded {
6✔
1608
                msg := fmt.Sprintf("unable to operate on commitment with a state of %s", dbCommitment.State)
1✔
1609
                http.Error(w, msg, http.StatusForbidden)
1✔
1610
                return
1✔
1611
        }
1✔
1612

1613
        var loc core.AZResourceLocation
4✔
1614
        err = p.DB.QueryRow(findClusterAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
4✔
1615
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
4✔
1616
        if errors.Is(err, sql.ErrNoRows) {
4✔
1617
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1618
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1619
                return
×
1620
        } else if respondwith.ErrorText(w, err) {
4✔
1621
                return
×
1622
        }
×
1623
        behavior := p.Cluster.CommitmentBehaviorForResource(loc.ServiceType, loc.ResourceName).ForDomain(dbDomain.Name)
4✔
1624
        if !slices.Contains(behavior.Durations, req.Duration) {
5✔
1625
                msg := fmt.Sprintf("provided duration: %s does not match the config %v", req.Duration, behavior.Durations)
1✔
1626
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1627
                return
1✔
1628
        }
1✔
1629

1630
        newExpiresAt := req.Duration.AddTo(dbCommitment.ConfirmBy.UnwrapOr(dbCommitment.CreatedAt))
3✔
1631
        if newExpiresAt.Before(dbCommitment.ExpiresAt) {
4✔
1632
                msg := fmt.Sprintf("duration change from %s to %s forbidden", dbCommitment.Duration, req.Duration)
1✔
1633
                http.Error(w, msg, http.StatusForbidden)
1✔
1634
                return
1✔
1635
        }
1✔
1636

1637
        dbCommitment.Duration = req.Duration
2✔
1638
        dbCommitment.ExpiresAt = newExpiresAt
2✔
1639
        _, err = p.DB.Update(&dbCommitment)
2✔
1640
        if respondwith.ErrorText(w, err) {
2✔
1641
                return
×
1642
        }
×
1643

1644
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
2✔
1645
        if respondwith.ErrorText(w, err) {
2✔
1646
                return
×
1647
        }
×
1648
        serviceInfo, ok := maybeServiceInfo.Unpack()
2✔
1649
        if !ok {
2✔
1650
                http.Error(w, "service not found", http.StatusNotFound)
×
1651
                return
×
1652
        }
×
1653
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
2✔
1654
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
2✔
1655
        p.auditor.Record(audittools.Event{
2✔
1656
                Time:       p.timeNow(),
2✔
1657
                Request:    r,
2✔
1658
                User:       token,
2✔
1659
                ReasonCode: http.StatusOK,
2✔
1660
                Action:     cadf.UpdateAction,
2✔
1661
                Target: commitmentEventTarget{
2✔
1662
                        DomainID:    dbDomain.UUID,
2✔
1663
                        DomainName:  dbDomain.Name,
2✔
1664
                        ProjectID:   dbProject.UUID,
2✔
1665
                        ProjectName: dbProject.Name,
2✔
1666
                        Commitments: []limesresources.Commitment{c},
2✔
1667
                },
2✔
1668
        })
2✔
1669

2✔
1670
        respondwith.JSON(w, http.StatusOK, map[string]any{"commitment": c})
2✔
1671
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc