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

sapcc / limes / 13566133527

27 Feb 2025 12:15PM UTC coverage: 79.46% (+0.04%) from 79.417%
13566133527

push

github

web-flow
Merge pull request #661 from sapcc/commitment-merging

add api endpoint for commitment merging

215 of 252 new or added lines in 5 files covered. (85.32%)

1 existing line in 1 file now uncovered.

5915 of 7444 relevant lines covered (79.46%)

62.26 hits per line

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

79.34
/internal/api/commitment.go
1
/******************************************************************************
2
*
3
*  Copyright 2023 SAP SE
4
*
5
*  Licensed under the Apache License, Version 2.0 (the "License");
6
*  you may not use this file except in compliance with the License.
7
*  You may obtain a copy of the License at
8
*
9
*      http://www.apache.org/licenses/LICENSE-2.0
10
*
11
*  Unless required by applicable law or agreed to in writing, software
12
*  distributed under the License is distributed on an "AS IS" BASIS,
13
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
*  See the License for the specific language governing permissions and
15
*  limitations under the License.
16
*
17
******************************************************************************/
18

19
package api
20

21
import (
22
        "database/sql"
23
        "encoding/json"
24
        "errors"
25
        "fmt"
26
        "net/http"
27
        "slices"
28
        "strings"
29
        "time"
30

31
        "github.com/gorilla/mux"
32
        "github.com/sapcc/go-api-declarations/cadf"
33
        "github.com/sapcc/go-api-declarations/limes"
34
        limesresources "github.com/sapcc/go-api-declarations/limes/resources"
35
        "github.com/sapcc/go-api-declarations/liquid"
36
        "github.com/sapcc/go-bits/audittools"
37
        "github.com/sapcc/go-bits/gopherpolicy"
38
        "github.com/sapcc/go-bits/httpapi"
39
        "github.com/sapcc/go-bits/must"
40
        "github.com/sapcc/go-bits/respondwith"
41
        "github.com/sapcc/go-bits/sqlext"
42

43
        "github.com/sapcc/limes/internal/core"
44
        "github.com/sapcc/limes/internal/datamodel"
45
        "github.com/sapcc/limes/internal/db"
46
        "github.com/sapcc/limes/internal/liquids"
47
        "github.com/sapcc/limes/internal/reports"
48
)
49

50
var (
51
        getProjectCommitmentsQuery = sqlext.SimplifyWhitespace(`
52
                SELECT pc.*
53
                  FROM project_commitments pc
54
                  JOIN project_az_resources par ON pc.az_resource_id = par.id
55
                  JOIN project_resources pr ON par.resource_id = pr.id {{AND pr.name = $resource_name}}
56
                  JOIN project_services ps ON pr.service_id = ps.id {{AND ps.type = $service_type}}
57
                 WHERE %s AND pc.state NOT IN ('superseded', 'expired')
58
                 ORDER BY pc.id
59
        `)
60

61
        getProjectAZResourceLocationsQuery = sqlext.SimplifyWhitespace(`
62
                SELECT par.id, ps.type, pr.name, par.az
63
                  FROM project_az_resources par
64
                  JOIN project_resources pr ON par.resource_id = pr.id {{AND pr.name = $resource_name}}
65
                  JOIN project_services ps ON pr.service_id = ps.id {{AND ps.type = $service_type}}
66
                 WHERE %s
67
        `)
68

69
        findProjectCommitmentByIDQuery = sqlext.SimplifyWhitespace(`
70
                SELECT pc.*
71
                  FROM project_commitments pc
72
                  JOIN project_az_resources par ON pc.az_resource_id = par.id
73
                  JOIN project_resources pr ON par.resource_id = pr.id
74
                  JOIN project_services ps ON pr.service_id = ps.id
75
                 WHERE pc.id = $1 AND ps.project_id = $2
76
        `)
77

78
        // NOTE: The third output column is `resourceAllowsCommitments`.
79
        // We should be checking for `ResourceUsageReport.Forbidden == true`, but
80
        // since the `Forbidden` field is not persisted in the DB, we need to use
81
        // `max_quota_from_backend` as a proxy.
82
        findProjectAZResourceIDByLocationQuery = sqlext.SimplifyWhitespace(`
83
                SELECT pr.id, par.id, pr.max_quota_from_backend IS NULL
84
                  FROM project_az_resources par
85
                  JOIN project_resources pr ON par.resource_id = pr.id
86
                  JOIN project_services ps ON pr.service_id = ps.id
87
                 WHERE ps.project_id = $1 AND ps.type = $2 AND pr.name = $3 AND par.az = $4
88
        `)
89

90
        findProjectAZResourceLocationByIDQuery = sqlext.SimplifyWhitespace(`
91
                SELECT ps.type, pr.name, par.az
92
                  FROM project_az_resources par
93
                  JOIN project_resources pr ON par.resource_id = pr.id
94
                  JOIN project_services ps ON pr.service_id = ps.id
95
                 WHERE par.id = $1
96
        `)
97
        getCommitmentWithMatchingTransferTokenQuery = sqlext.SimplifyWhitespace(`
98
                SELECT * FROM project_commitments WHERE id = $1 AND transfer_token = $2
99
        `)
100
        findCommitmentByTransferToken = sqlext.SimplifyWhitespace(`
101
                SELECT * FROM project_commitments WHERE transfer_token = $1
102
        `)
103
        findTargetAZResourceIDBySourceIDQuery = sqlext.SimplifyWhitespace(`
104
                WITH source as (
105
                SELECT pr.id AS resource_id, ps.type, pr.name, par.az
106
                  FROM project_az_resources as par
107
                  JOIN project_resources pr ON par.resource_id = pr.id
108
                  JOIN project_services ps ON pr.service_id = ps.id
109
                 WHERE par.id = $1
110
                )
111
                SELECT s.resource_id, pr.id, par.id
112
                  FROM project_az_resources as par
113
                  JOIN project_resources pr ON par.resource_id = pr.id
114
                  JOIN project_services ps ON pr.service_id = ps.id
115
                  JOIN source s ON ps.type = s.type AND pr.name = s.name AND par.az = s.az
116
                 WHERE ps.project_id = $2
117
        `)
118
        findTargetAZResourceByTargetProjectQuery = sqlext.SimplifyWhitespace(`
119
                SELECT pr.id, par.id
120
                  FROM project_az_resources par
121
                  JOIN project_resources pr ON par.resource_id = pr.id
122
                  JOIN project_services ps ON pr.service_id = ps.id
123
                 WHERE ps.project_id = $1 AND ps.type = $2 AND pr.name = $3 AND par.az = $4
124
        `)
125
        forceImmediateCapacityScrapeQuery = sqlext.SimplifyWhitespace(`
126
                UPDATE cluster_capacitors SET next_scrape_at = $1 WHERE capacitor_id = (
127
                        SELECT capacitor_id FROM cluster_services cs JOIN cluster_resources cr ON cs.id = cr.service_id
128
                        WHERE cs.type = $2 AND cr.name = $3
129
                )
130
        `)
131
)
132

133
// GetProjectCommitments handles GET /v1/domains/:domain_id/projects/:project_id/commitments.
134
func (p *v1Provider) GetProjectCommitments(w http.ResponseWriter, r *http.Request) {
15✔
135
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments")
15✔
136
        token := p.CheckToken(r)
15✔
137
        if !token.Require(w, "project:show") {
16✔
138
                return
1✔
139
        }
1✔
140
        dbDomain := p.FindDomainFromRequest(w, r)
14✔
141
        if dbDomain == nil {
15✔
142
                return
1✔
143
        }
1✔
144
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
13✔
145
        if dbProject == nil {
14✔
146
                return
1✔
147
        }
1✔
148

149
        // enumerate project AZ resources
150
        filter := reports.ReadFilter(r, p.Cluster)
12✔
151
        queryStr, joinArgs := filter.PrepareQuery(getProjectAZResourceLocationsQuery)
12✔
152
        whereStr, whereArgs := db.BuildSimpleWhereClause(map[string]any{"ps.project_id": dbProject.ID}, len(joinArgs))
12✔
153
        azResourceLocationsByID := make(map[db.ProjectAZResourceID]core.AZResourceLocation)
12✔
154
        err := sqlext.ForeachRow(p.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {
137✔
155
                var (
125✔
156
                        id  db.ProjectAZResourceID
125✔
157
                        loc core.AZResourceLocation
125✔
158
                )
125✔
159
                err := rows.Scan(&id, &loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
125✔
160
                if err != nil {
125✔
161
                        return err
×
162
                }
×
163
                // this check is defense in depth (the DB should be consistent with our config)
164
                if p.Cluster.HasResource(loc.ServiceType, loc.ResourceName) {
250✔
165
                        azResourceLocationsByID[id] = loc
125✔
166
                }
125✔
167
                return nil
125✔
168
        })
169
        if respondwith.ErrorText(w, err) {
12✔
170
                return
×
171
        }
×
172

173
        // enumerate relevant project commitments
174
        queryStr, joinArgs = filter.PrepareQuery(getProjectCommitmentsQuery)
12✔
175
        whereStr, whereArgs = db.BuildSimpleWhereClause(map[string]any{"ps.project_id": dbProject.ID}, len(joinArgs))
12✔
176
        var dbCommitments []db.ProjectCommitment
12✔
177
        _, err = p.DB.Select(&dbCommitments, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...)...)
12✔
178
        if respondwith.ErrorText(w, err) {
12✔
179
                return
×
180
        }
×
181

182
        // render response
183
        result := make([]limesresources.Commitment, 0, len(dbCommitments))
12✔
184
        for _, c := range dbCommitments {
26✔
185
                loc, exists := azResourceLocationsByID[c.AZResourceID]
14✔
186
                if !exists {
14✔
187
                        // defense in depth (the DB should not change that much between those two queries above)
×
188
                        continue
×
189
                }
190
                result = append(result, p.convertCommitmentToDisplayForm(c, loc, token))
14✔
191
        }
192

193
        respondwith.JSON(w, http.StatusOK, map[string]any{"commitments": result})
12✔
194
}
195

196
func (p *v1Provider) convertCommitmentToDisplayForm(c db.ProjectCommitment, loc core.AZResourceLocation, token *gopherpolicy.Token) limesresources.Commitment {
75✔
197
        resInfo := p.Cluster.InfoForResource(loc.ServiceType, loc.ResourceName)
75✔
198
        apiIdentity := p.Cluster.BehaviorForResource(loc.ServiceType, loc.ResourceName).IdentityInV1API
75✔
199
        return limesresources.Commitment{
75✔
200
                ID:               int64(c.ID),
75✔
201
                ServiceType:      apiIdentity.ServiceType,
75✔
202
                ResourceName:     apiIdentity.Name,
75✔
203
                AvailabilityZone: loc.AvailabilityZone,
75✔
204
                Amount:           c.Amount,
75✔
205
                Unit:             resInfo.Unit,
75✔
206
                Duration:         c.Duration,
75✔
207
                CreatedAt:        limes.UnixEncodedTime{Time: c.CreatedAt},
75✔
208
                CreatorUUID:      c.CreatorUUID,
75✔
209
                CreatorName:      c.CreatorName,
75✔
210
                CanBeDeleted:     p.canDeleteCommitment(token, c),
75✔
211
                ConfirmBy:        maybeUnixEncodedTime(c.ConfirmBy),
75✔
212
                ConfirmedAt:      maybeUnixEncodedTime(c.ConfirmedAt),
75✔
213
                ExpiresAt:        limes.UnixEncodedTime{Time: c.ExpiresAt},
75✔
214
                TransferStatus:   c.TransferStatus,
75✔
215
                TransferToken:    c.TransferToken,
75✔
216
        }
75✔
217
}
75✔
218

219
func (p *v1Provider) parseAndValidateCommitmentRequest(w http.ResponseWriter, r *http.Request) (*limesresources.CommitmentRequest, *core.AZResourceLocation, *core.ResourceBehavior) {
42✔
220
        // parse request
42✔
221
        var parseTarget struct {
42✔
222
                Request limesresources.CommitmentRequest `json:"commitment"`
42✔
223
        }
42✔
224
        if !RequireJSON(w, r, &parseTarget) {
43✔
225
                return nil, nil, nil
1✔
226
        }
1✔
227
        req := parseTarget.Request
41✔
228

41✔
229
        // validate request
41✔
230
        nm := core.BuildResourceNameMapping(p.Cluster)
41✔
231
        dbServiceType, dbResourceName, ok := nm.MapFromV1API(req.ServiceType, req.ResourceName)
41✔
232
        if !ok {
43✔
233
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", req.ServiceType, req.ResourceName)
2✔
234
                http.Error(w, msg, http.StatusUnprocessableEntity)
2✔
235
                return nil, nil, nil
2✔
236
        }
2✔
237
        behavior := p.Cluster.BehaviorForResource(dbServiceType, dbResourceName)
39✔
238
        resInfo := p.Cluster.InfoForResource(dbServiceType, dbResourceName)
39✔
239
        if len(behavior.CommitmentDurations) == 0 {
40✔
240
                http.Error(w, "commitments are not enabled for this resource", http.StatusUnprocessableEntity)
1✔
241
                return nil, nil, nil
1✔
242
        }
1✔
243
        if resInfo.Topology == liquid.FlatResourceTopology {
41✔
244
                if req.AvailabilityZone != limes.AvailabilityZoneAny {
4✔
245
                        http.Error(w, `resource does not accept AZ-aware commitments, so the AZ must be set to "any"`, http.StatusUnprocessableEntity)
1✔
246
                        return nil, nil, nil
1✔
247
                }
1✔
248
        } else {
35✔
249
                if !slices.Contains(p.Cluster.Config.AvailabilityZones, req.AvailabilityZone) {
39✔
250
                        http.Error(w, "no such availability zone", http.StatusUnprocessableEntity)
4✔
251
                        return nil, nil, nil
4✔
252
                }
4✔
253
        }
254
        if !slices.Contains(behavior.CommitmentDurations, req.Duration) {
34✔
255
                buf := must.Return(json.Marshal(behavior.CommitmentDurations)) // panic on error is acceptable here, marshals should never fail
1✔
256
                msg := "unacceptable commitment duration for this resource, acceptable values: " + string(buf)
1✔
257
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
258
                return nil, nil, nil
1✔
259
        }
1✔
260
        if req.Amount == 0 {
33✔
261
                http.Error(w, "amount of committed resource must be greater than zero", http.StatusUnprocessableEntity)
1✔
262
                return nil, nil, nil
1✔
263
        }
1✔
264

265
        loc := core.AZResourceLocation{
31✔
266
                ServiceType:      dbServiceType,
31✔
267
                ResourceName:     dbResourceName,
31✔
268
                AvailabilityZone: req.AvailabilityZone,
31✔
269
        }
31✔
270
        return &req, &loc, &behavior
31✔
271
}
272

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

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

7✔
310
        // commitments can never be confirmed immediately if we are before the min_confirm_date
7✔
311
        now := p.timeNow()
7✔
312
        if behavior.CommitmentMinConfirmDate != nil && behavior.CommitmentMinConfirmDate.After(now) {
8✔
313
                respondwith.JSON(w, http.StatusOK, map[string]bool{"result": false})
1✔
314
                return
1✔
315
        }
1✔
316

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

325
// CreateProjectCommitment handles POST /v1/domains/:domain_id/projects/:project_id/commitments/new.
326
func (p *v1Provider) CreateProjectCommitment(w http.ResponseWriter, r *http.Request) {
38✔
327
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/new")
38✔
328
        token := p.CheckToken(r)
38✔
329
        if !token.Require(w, "project:edit") {
39✔
330
                return
1✔
331
        }
1✔
332
        dbDomain := p.FindDomainFromRequest(w, r)
37✔
333
        if dbDomain == nil {
38✔
334
                return
1✔
335
        }
1✔
336
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
36✔
337
        if dbProject == nil {
37✔
338
                return
1✔
339
        }
1✔
340
        req, loc, behavior := p.parseAndValidateCommitmentRequest(w, r)
35✔
341
        if req == nil {
46✔
342
                return
11✔
343
        }
11✔
344

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

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

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

21✔
382
        // prepare commitment
21✔
383
        confirmBy := maybeUnpackUnixEncodedTime(req.ConfirmBy)
21✔
384
        creationContext := db.CommitmentWorkflowContext{Reason: db.CommitmentReasonCreate}
21✔
385
        buf, err := json.Marshal(creationContext)
21✔
386
        if respondwith.ErrorText(w, err) {
21✔
NEW
387
                return
×
NEW
388
        }
×
389
        dbCommitment := db.ProjectCommitment{
21✔
390
                AZResourceID:        azResourceID,
21✔
391
                Amount:              req.Amount,
21✔
392
                Duration:            req.Duration,
21✔
393
                CreatedAt:           now,
21✔
394
                CreatorUUID:         token.UserUUID(),
21✔
395
                CreatorName:         fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
21✔
396
                ConfirmBy:           confirmBy,
21✔
397
                ConfirmedAt:         nil, // may be set below
21✔
398
                ExpiresAt:           req.Duration.AddTo(unwrapOrDefault(confirmBy, now)),
21✔
399
                CreationContextJSON: json.RawMessage(buf),
21✔
400
        }
21✔
401
        if req.ConfirmBy == nil {
36✔
402
                // if not planned for confirmation in the future, confirm immediately (or fail)
15✔
403
                ok, err := datamodel.CanConfirmNewCommitment(*loc, resourceID, req.Amount, p.Cluster, tx)
15✔
404
                if respondwith.ErrorText(w, err) {
15✔
405
                        return
×
406
                }
×
407
                if !ok {
15✔
408
                        http.Error(w, "not enough capacity available for immediate confirmation", http.StatusConflict)
×
409
                        return
×
410
                }
×
411
                dbCommitment.ConfirmedAt = &now
15✔
412
                dbCommitment.State = db.CommitmentStateActive
15✔
413
        } else {
6✔
414
                dbCommitment.State = db.CommitmentStatePlanned
6✔
415
        }
6✔
416

417
        // create commitment
418
        err = tx.Insert(&dbCommitment)
21✔
419
        if respondwith.ErrorText(w, err) {
21✔
420
                return
×
421
        }
×
422
        err = tx.Commit()
21✔
423
        if respondwith.ErrorText(w, err) {
21✔
424
                return
×
425
        }
×
426
        p.auditor.Record(audittools.Event{
21✔
427
                Time:       now,
21✔
428
                Request:    r,
21✔
429
                User:       token,
21✔
430
                ReasonCode: http.StatusCreated,
21✔
431
                Action:     cadf.CreateAction,
21✔
432
                Target: commitmentEventTarget{
21✔
433
                        DomainID:        dbDomain.UUID,
21✔
434
                        DomainName:      dbDomain.Name,
21✔
435
                        ProjectID:       dbProject.UUID,
21✔
436
                        ProjectName:     dbProject.Name,
21✔
437
                        Commitments:     []limesresources.Commitment{p.convertCommitmentToDisplayForm(dbCommitment, *loc, token)},
21✔
438
                        WorkflowContext: &creationContext,
21✔
439
                },
21✔
440
        })
21✔
441

21✔
442
        // if the commitment is immediately confirmed, trigger a capacity scrape in
21✔
443
        // order to ApplyComputedProjectQuotas based on the new commitment
21✔
444
        if dbCommitment.ConfirmedAt != nil {
36✔
445
                _, err := p.DB.Exec(forceImmediateCapacityScrapeQuery, now, loc.ServiceType, loc.ResourceName)
15✔
446
                if respondwith.ErrorText(w, err) {
15✔
447
                        return
×
448
                }
×
449
        }
450

451
        // display the possibly confirmed commitment to the user
452
        err = p.DB.SelectOne(&dbCommitment, `SELECT * FROM project_commitments WHERE id = $1`, dbCommitment.ID)
21✔
453
        if respondwith.ErrorText(w, err) {
21✔
454
                return
×
455
        }
×
456

457
        c := p.convertCommitmentToDisplayForm(dbCommitment, *loc, token)
21✔
458
        respondwith.JSON(w, http.StatusCreated, map[string]any{"commitment": c})
21✔
459
}
460

461
// MergeProjectCommitments handles POST /v1/domains/:domain_id/projects/:project_id/commitments/merge.
462
func (p *v1Provider) MergeProjectCommitments(w http.ResponseWriter, r *http.Request) {
12✔
463
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/merge")
12✔
464
        token := p.CheckToken(r)
12✔
465
        if !token.Require(w, "project:edit") {
13✔
466
                return
1✔
467
        }
1✔
468
        dbDomain := p.FindDomainFromRequest(w, r)
11✔
469
        if dbDomain == nil {
12✔
470
                return
1✔
471
        }
1✔
472
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
10✔
473
        if dbProject == nil {
11✔
474
                return
1✔
475
        }
1✔
476
        var parseTarget struct {
9✔
477
                CommitmentIDs []db.ProjectCommitmentID `json:"commitment_ids"`
9✔
478
        }
9✔
479
        if !RequireJSON(w, r, &parseTarget) {
9✔
NEW
480
                return
×
NEW
481
        }
×
482
        commitmentIDs := parseTarget.CommitmentIDs
9✔
483
        if len(commitmentIDs) < 2 {
10✔
484
                http.Error(w, fmt.Sprintf("merging requires at least two commitments, but %d were given", len(commitmentIDs)), http.StatusBadRequest)
1✔
485
                return
1✔
486
        }
1✔
487

488
        // Load commitments
489
        dbCommitments := make([]db.ProjectCommitment, len(commitmentIDs))
8✔
490
        for i, commitmentID := range commitmentIDs {
24✔
491
                err := p.DB.SelectOne(&dbCommitments[i], findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
16✔
492
                if errors.Is(err, sql.ErrNoRows) {
17✔
493
                        http.Error(w, "no such commitment", http.StatusNotFound)
1✔
494
                        return
1✔
495
                } else if respondwith.ErrorText(w, err) {
16✔
NEW
496
                        return
×
NEW
497
                }
×
498
        }
499

500
        // Verify that all commitments agree on resource and AZ and are active
501
        azResourceID := dbCommitments[0].AZResourceID
7✔
502
        for _, dbCommitment := range dbCommitments {
21✔
503
                if dbCommitment.AZResourceID != azResourceID {
16✔
504
                        http.Error(w, "all commitments must be on the same resource and AZ", http.StatusConflict)
2✔
505
                        return
2✔
506
                }
2✔
507
                if dbCommitment.State != db.CommitmentStateActive {
16✔
508
                        http.Error(w, "only active commitments may be merged", http.StatusConflict)
4✔
509
                        return
4✔
510
                }
4✔
511
        }
512

513
        var loc core.AZResourceLocation
1✔
514
        err := p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, azResourceID).
1✔
515
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
1✔
516
        if errors.Is(err, sql.ErrNoRows) {
1✔
NEW
517
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
NEW
518
                return
×
519
        } else if respondwith.ErrorText(w, err) {
1✔
NEW
520
                return
×
NEW
521
        }
×
522

523
        // Start transaction for creating new commitment and marking merged commitments as superseded
524
        tx, err := p.DB.Begin()
1✔
525
        if respondwith.ErrorText(w, err) {
1✔
NEW
526
                return
×
NEW
527
        }
×
528
        defer sqlext.RollbackUnlessCommitted(tx)
1✔
529

1✔
530
        // Create merged template
1✔
531
        now := p.timeNow()
1✔
532
        dbMergedCommitment := db.ProjectCommitment{
1✔
533
                AZResourceID: azResourceID,
1✔
534
                Amount:       0,                                   // overwritten below
1✔
535
                Duration:     limesresources.CommitmentDuration{}, // overwritten below
1✔
536
                CreatedAt:    now,
1✔
537
                CreatorUUID:  token.UserUUID(),
1✔
538
                CreatorName:  fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
1✔
539
                ConfirmedAt:  &now,
1✔
540
                ExpiresAt:    time.Time{}, // overwritten below
1✔
541
                State:        db.CommitmentStateActive,
1✔
542
        }
1✔
543

1✔
544
        // Fill amount and latest expiration date
1✔
545
        for _, dbCommitment := range dbCommitments {
3✔
546
                dbMergedCommitment.Amount += dbCommitment.Amount
2✔
547
                if dbCommitment.ExpiresAt.After(dbMergedCommitment.ExpiresAt) {
4✔
548
                        dbMergedCommitment.ExpiresAt = dbCommitment.ExpiresAt
2✔
549
                        dbMergedCommitment.Duration = dbCommitment.Duration
2✔
550
                }
2✔
551
        }
552

553
        // Fill workflow context
554
        creationContext := db.CommitmentWorkflowContext{
1✔
555
                Reason:               db.CommitmentReasonMerge,
1✔
556
                RelatedCommitmentIDs: commitmentIDs,
1✔
557
        }
1✔
558
        buf, err := json.Marshal(creationContext)
1✔
559
        if respondwith.ErrorText(w, err) {
1✔
NEW
560
                return
×
NEW
561
        }
×
562
        dbMergedCommitment.CreationContextJSON = json.RawMessage(buf)
1✔
563

1✔
564
        // Insert into database
1✔
565
        err = tx.Insert(&dbMergedCommitment)
1✔
566
        if respondwith.ErrorText(w, err) {
1✔
NEW
567
                return
×
NEW
568
        }
×
569

570
        // Mark merged commits as superseded
571
        supersedeContext := db.CommitmentWorkflowContext{
1✔
572
                Reason:               db.CommitmentReasonMerge,
1✔
573
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbMergedCommitment.ID},
1✔
574
        }
1✔
575
        buf, err = json.Marshal(supersedeContext)
1✔
576
        if respondwith.ErrorText(w, err) {
1✔
NEW
577
                return
×
NEW
578
        }
×
579
        for _, dbCommitment := range dbCommitments {
3✔
580
                dbCommitment.SupersededAt = &now
2✔
581
                dbCommitment.SupersedeContextJSON = liquids.PointerTo(json.RawMessage(buf))
2✔
582
                dbCommitment.State = db.CommitmentStateSuperseded
2✔
583
                _, err = tx.Update(&dbCommitment)
2✔
584
                if respondwith.ErrorText(w, err) {
2✔
NEW
585
                        return
×
NEW
586
                }
×
587
        }
588

589
        err = tx.Commit()
1✔
590
        if respondwith.ErrorText(w, err) {
1✔
NEW
591
                return
×
NEW
592
        }
×
593

594
        c := p.convertCommitmentToDisplayForm(dbMergedCommitment, loc, token)
1✔
595
        auditEvent := commitmentEventTarget{
1✔
596
                DomainID:        dbDomain.UUID,
1✔
597
                DomainName:      dbDomain.Name,
1✔
598
                ProjectID:       dbProject.UUID,
1✔
599
                ProjectName:     dbProject.Name,
1✔
600
                Commitments:     []limesresources.Commitment{c},
1✔
601
                WorkflowContext: &creationContext,
1✔
602
        }
1✔
603
        p.auditor.Record(audittools.Event{
1✔
604
                Time:       p.timeNow(),
1✔
605
                Request:    r,
1✔
606
                User:       token,
1✔
607
                ReasonCode: http.StatusAccepted,
1✔
608
                Action:     cadf.UpdateAction,
1✔
609
                Target:     auditEvent,
1✔
610
        })
1✔
611

1✔
612
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
613
}
614

615
// DeleteProjectCommitment handles DELETE /v1/domains/:domain_id/projects/:project_id/commitments/:id.
616
func (p *v1Provider) DeleteProjectCommitment(w http.ResponseWriter, r *http.Request) {
8✔
617
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id")
8✔
618
        token := p.CheckToken(r)
8✔
619
        if !token.Require(w, "project:edit") { //NOTE: There is a more specific AuthZ check further down below.
8✔
620
                return
×
621
        }
×
622
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
623
        if dbDomain == nil {
9✔
624
                return
1✔
625
        }
1✔
626
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
7✔
627
        if dbProject == nil {
8✔
628
                return
1✔
629
        }
1✔
630

631
        // load commitment
632
        var dbCommitment db.ProjectCommitment
6✔
633
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
6✔
634
        if errors.Is(err, sql.ErrNoRows) {
7✔
635
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
636
                return
1✔
637
        } else if respondwith.ErrorText(w, err) {
6✔
638
                return
×
639
        }
×
640
        var loc core.AZResourceLocation
5✔
641
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
5✔
642
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
5✔
643
        if errors.Is(err, sql.ErrNoRows) {
5✔
644
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
645
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
646
                return
×
647
        } else if respondwith.ErrorText(w, err) {
5✔
648
                return
×
649
        }
×
650

651
        // check authorization for this specific commitment
652
        if !p.canDeleteCommitment(token, dbCommitment) {
6✔
653
                http.Error(w, "Forbidden", http.StatusForbidden)
1✔
654
                return
1✔
655
        }
1✔
656

657
        // perform deletion
658
        _, err = p.DB.Delete(&dbCommitment)
4✔
659
        if respondwith.ErrorText(w, err) {
4✔
660
                return
×
661
        }
×
662
        p.auditor.Record(audittools.Event{
4✔
663
                Time:       p.timeNow(),
4✔
664
                Request:    r,
4✔
665
                User:       token,
4✔
666
                ReasonCode: http.StatusNoContent,
4✔
667
                Action:     cadf.DeleteAction,
4✔
668
                Target: commitmentEventTarget{
4✔
669
                        DomainID:    dbDomain.UUID,
4✔
670
                        DomainName:  dbDomain.Name,
4✔
671
                        ProjectID:   dbProject.UUID,
4✔
672
                        ProjectName: dbProject.Name,
4✔
673
                        Commitments: []limesresources.Commitment{p.convertCommitmentToDisplayForm(dbCommitment, loc, token)},
4✔
674
                },
4✔
675
        })
4✔
676

4✔
677
        w.WriteHeader(http.StatusNoContent)
4✔
678
}
679

680
func (p *v1Provider) canDeleteCommitment(token *gopherpolicy.Token, commitment db.ProjectCommitment) bool {
80✔
681
        // up to 24 hours after creation of fresh commitments, future commitments can still be deleted by their creators
80✔
682
        if commitment.State == db.CommitmentStatePlanned || commitment.State == db.CommitmentStatePending || commitment.State == db.CommitmentStateActive {
160✔
683
                var creationContext db.CommitmentWorkflowContext
80✔
684
                err := json.Unmarshal(commitment.CreationContextJSON, &creationContext)
80✔
685
                if err == nil && creationContext.Reason == db.CommitmentReasonCreate && p.timeNow().Before(commitment.CreatedAt.Add(24*time.Hour)) {
138✔
686
                        if token.Check("project:edit") {
116✔
687
                                return true
58✔
688
                        }
58✔
689
                }
690
        }
691

692
        // afterwards, a more specific permission is required to delete it
693
        //
694
        // This protects cloud admins making capacity planning decisions based on future commitments
695
        // from having their forecasts ruined by project admins suffering from buyer's remorse.
696
        return token.Check("project:uncommit")
22✔
697
}
698

699
// StartCommitmentTransfer handles POST /v1/domains/:id/projects/:id/commitments/:id/start-transfer
700
func (p *v1Provider) StartCommitmentTransfer(w http.ResponseWriter, r *http.Request) {
8✔
701
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id/start-transfer")
8✔
702
        token := p.CheckToken(r)
8✔
703
        if !token.Require(w, "project:edit") {
8✔
704
                return
×
705
        }
×
706
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
707
        if dbDomain == nil {
8✔
708
                return
×
709
        }
×
710
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
8✔
711
        if dbProject == nil {
8✔
712
                return
×
713
        }
×
714
        // TODO: eventually migrate this struct into go-api-declarations
715
        var parseTarget struct {
8✔
716
                Request struct {
8✔
717
                        Amount         uint64                                  `json:"amount"`
8✔
718
                        TransferStatus limesresources.CommitmentTransferStatus `json:"transfer_status,omitempty"`
8✔
719
                } `json:"commitment"`
8✔
720
        }
8✔
721
        if !RequireJSON(w, r, &parseTarget) {
8✔
722
                return
×
723
        }
×
724
        req := parseTarget.Request
8✔
725

8✔
726
        if req.TransferStatus != limesresources.CommitmentTransferStatusUnlisted && req.TransferStatus != limesresources.CommitmentTransferStatusPublic {
8✔
727
                http.Error(w, fmt.Sprintf("Invalid transfer_status code. Must be %s or %s.", limesresources.CommitmentTransferStatusUnlisted, limesresources.CommitmentTransferStatusPublic), http.StatusBadRequest)
×
728
                return
×
729
        }
×
730

731
        if req.Amount <= 0 {
9✔
732
                http.Error(w, "delivered amount needs to be a positive value.", http.StatusBadRequest)
1✔
733
                return
1✔
734
        }
1✔
735

736
        // load commitment
737
        var dbCommitment db.ProjectCommitment
7✔
738
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
7✔
739
        if errors.Is(err, sql.ErrNoRows) {
7✔
740
                http.Error(w, "no such commitment", http.StatusNotFound)
×
741
                return
×
742
        } else if respondwith.ErrorText(w, err) {
7✔
743
                return
×
744
        }
×
745

746
        // Mark whole commitment or a newly created, splitted one as transferrable.
747
        tx, err := p.DB.Begin()
7✔
748
        if respondwith.ErrorText(w, err) {
7✔
749
                return
×
750
        }
×
751
        defer sqlext.RollbackUnlessCommitted(tx)
7✔
752
        transferToken := p.generateTransferToken()
7✔
753

7✔
754
        // Deny requests with a greater amount than the commitment.
7✔
755
        if req.Amount > dbCommitment.Amount {
8✔
756
                http.Error(w, "delivered amount exceeds the commitment amount.", http.StatusBadRequest)
1✔
757
                return
1✔
758
        }
1✔
759

760
        if req.Amount == dbCommitment.Amount {
10✔
761
                dbCommitment.TransferStatus = req.TransferStatus
4✔
762
                dbCommitment.TransferToken = &transferToken
4✔
763
                _, err = tx.Update(&dbCommitment)
4✔
764
                if respondwith.ErrorText(w, err) {
4✔
765
                        return
×
766
                }
×
767
        } else {
2✔
768
                now := p.timeNow()
2✔
769
                transferAmount := req.Amount
2✔
770
                remainingAmount := dbCommitment.Amount - req.Amount
2✔
771
                transferCommitment, err := p.buildSplitCommitment(dbCommitment, transferAmount)
2✔
772
                if respondwith.ErrorText(w, err) {
2✔
NEW
773
                        return
×
NEW
774
                }
×
775
                transferCommitment.TransferStatus = req.TransferStatus
2✔
776
                transferCommitment.TransferToken = &transferToken
2✔
777
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
2✔
778
                if respondwith.ErrorText(w, err) {
2✔
NEW
779
                        return
×
NEW
780
                }
×
781
                err = tx.Insert(&transferCommitment)
2✔
782
                if respondwith.ErrorText(w, err) {
2✔
783
                        return
×
784
                }
×
785
                err = tx.Insert(&remainingCommitment)
2✔
786
                if respondwith.ErrorText(w, err) {
2✔
787
                        return
×
788
                }
×
789
                supersedeContext := db.CommitmentWorkflowContext{
2✔
790
                        Reason:               db.CommitmentReasonSplit,
2✔
791
                        RelatedCommitmentIDs: []db.ProjectCommitmentID{transferCommitment.ID, remainingCommitment.ID},
2✔
792
                }
2✔
793
                buf, err := json.Marshal(supersedeContext)
2✔
794
                if respondwith.ErrorText(w, err) {
2✔
NEW
795
                        return
×
NEW
796
                }
×
797
                dbCommitment.State = db.CommitmentStateSuperseded
2✔
798
                dbCommitment.SupersededAt = &now
2✔
799
                dbCommitment.SupersedeContextJSON = liquids.PointerTo(json.RawMessage(buf))
2✔
800
                _, err = tx.Update(&dbCommitment)
2✔
801
                if respondwith.ErrorText(w, err) {
2✔
802
                        return
×
803
                }
×
804
                dbCommitment = transferCommitment
2✔
805
        }
806
        err = tx.Commit()
6✔
807
        if respondwith.ErrorText(w, err) {
6✔
808
                return
×
809
        }
×
810

811
        var loc core.AZResourceLocation
6✔
812
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
6✔
813
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
6✔
814
        if errors.Is(err, sql.ErrNoRows) {
6✔
815
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
816
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
817
                return
×
818
        } else if respondwith.ErrorText(w, err) {
6✔
819
                return
×
820
        }
×
821

822
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
6✔
823
        p.auditor.Record(audittools.Event{
6✔
824
                Time:       p.timeNow(),
6✔
825
                Request:    r,
6✔
826
                User:       token,
6✔
827
                ReasonCode: http.StatusAccepted,
6✔
828
                Action:     cadf.UpdateAction,
6✔
829
                Target: commitmentEventTarget{
6✔
830
                        DomainID:    dbDomain.UUID,
6✔
831
                        DomainName:  dbDomain.Name,
6✔
832
                        ProjectID:   dbProject.UUID,
6✔
833
                        ProjectName: dbProject.Name,
6✔
834
                        Commitments: []limesresources.Commitment{c},
6✔
835
                },
6✔
836
        })
6✔
837
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
6✔
838
}
839

840
func (p *v1Provider) buildSplitCommitment(dbCommitment db.ProjectCommitment, amount uint64) (db.ProjectCommitment, error) {
5✔
841
        now := p.timeNow()
5✔
842
        creationContext := db.CommitmentWorkflowContext{
5✔
843
                Reason:               db.CommitmentReasonSplit,
5✔
844
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
5✔
845
        }
5✔
846
        buf, err := json.Marshal(creationContext)
5✔
847
        if err != nil {
5✔
NEW
848
                return db.ProjectCommitment{}, err
×
UNCOV
849
        }
×
850
        return db.ProjectCommitment{
5✔
851
                AZResourceID:        dbCommitment.AZResourceID,
5✔
852
                Amount:              amount,
5✔
853
                Duration:            dbCommitment.Duration,
5✔
854
                CreatedAt:           now,
5✔
855
                CreatorUUID:         dbCommitment.CreatorUUID,
5✔
856
                CreatorName:         dbCommitment.CreatorName,
5✔
857
                ConfirmBy:           dbCommitment.ConfirmBy,
5✔
858
                ConfirmedAt:         dbCommitment.ConfirmedAt,
5✔
859
                ExpiresAt:           dbCommitment.ExpiresAt,
5✔
860
                CreationContextJSON: json.RawMessage(buf),
5✔
861
                State:               dbCommitment.State,
5✔
862
        }, nil
5✔
863
}
864

865
func (p *v1Provider) buildConvertedCommitment(dbCommitment db.ProjectCommitment, azResourceID db.ProjectAZResourceID, amount uint64) (db.ProjectCommitment, error) {
2✔
866
        now := p.timeNow()
2✔
867
        creationContext := db.CommitmentWorkflowContext{
2✔
868
                Reason:               db.CommitmentReasonConvert,
2✔
869
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
2✔
870
        }
2✔
871
        buf, err := json.Marshal(creationContext)
2✔
872
        if err != nil {
2✔
NEW
873
                return db.ProjectCommitment{}, err
×
NEW
874
        }
×
875
        return db.ProjectCommitment{
2✔
876
                AZResourceID:        azResourceID,
2✔
877
                Amount:              amount,
2✔
878
                Duration:            dbCommitment.Duration,
2✔
879
                CreatedAt:           now,
2✔
880
                CreatorUUID:         dbCommitment.CreatorUUID,
2✔
881
                CreatorName:         dbCommitment.CreatorName,
2✔
882
                ConfirmBy:           dbCommitment.ConfirmBy,
2✔
883
                ConfirmedAt:         dbCommitment.ConfirmedAt,
2✔
884
                ExpiresAt:           dbCommitment.ExpiresAt,
2✔
885
                CreationContextJSON: json.RawMessage(buf),
2✔
886
                State:               dbCommitment.State,
2✔
887
        }, nil
2✔
888
}
889

890
// GetCommitmentByTransferToken handles GET /v1/commitments/{token}
891
func (p *v1Provider) GetCommitmentByTransferToken(w http.ResponseWriter, r *http.Request) {
2✔
892
        httpapi.IdentifyEndpoint(r, "/v1/commitments/:token")
2✔
893
        token := p.CheckToken(r)
2✔
894
        if !token.Require(w, "cluster:show_basic") {
2✔
895
                return
×
896
        }
×
897
        transferToken := mux.Vars(r)["token"]
2✔
898

2✔
899
        // The token column is a unique key, so we expect only one result.
2✔
900
        var dbCommitment db.ProjectCommitment
2✔
901
        err := p.DB.SelectOne(&dbCommitment, findCommitmentByTransferToken, transferToken)
2✔
902
        if errors.Is(err, sql.ErrNoRows) {
3✔
903
                http.Error(w, "no matching commitment found.", http.StatusNotFound)
1✔
904
                return
1✔
905
        } else if respondwith.ErrorText(w, err) {
2✔
906
                return
×
907
        }
×
908

909
        var loc core.AZResourceLocation
1✔
910
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
1✔
911
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
1✔
912
        if errors.Is(err, sql.ErrNoRows) {
1✔
913
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
914
                http.Error(w, "location data not found.", http.StatusNotFound)
×
915
                return
×
916
        } else if respondwith.ErrorText(w, err) {
1✔
917
                return
×
918
        }
×
919

920
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
1✔
921
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
922
}
923

924
// TransferCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/transfer-commitment/{id}?token={token}
925
func (p *v1Provider) TransferCommitment(w http.ResponseWriter, r *http.Request) {
5✔
926
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/transfer-commitment/:id")
5✔
927
        token := p.CheckToken(r)
5✔
928
        if !token.Require(w, "project:edit") {
5✔
929
                return
×
930
        }
×
931
        transferToken := r.Header.Get("Transfer-Token")
5✔
932
        if transferToken == "" {
6✔
933
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
1✔
934
                return
1✔
935
        }
1✔
936
        commitmentID := mux.Vars(r)["id"]
4✔
937
        if commitmentID == "" {
4✔
938
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
939
                return
×
940
        }
×
941
        dbDomain := p.FindDomainFromRequest(w, r)
4✔
942
        if dbDomain == nil {
4✔
943
                return
×
944
        }
×
945
        targetProject := p.FindProjectFromRequest(w, r, dbDomain)
4✔
946
        if targetProject == nil {
4✔
947
                return
×
948
        }
×
949

950
        // find commitment by transfer_token
951
        var dbCommitment db.ProjectCommitment
4✔
952
        err := p.DB.SelectOne(&dbCommitment, getCommitmentWithMatchingTransferTokenQuery, commitmentID, transferToken)
4✔
953
        if errors.Is(err, sql.ErrNoRows) {
5✔
954
                http.Error(w, "no matching commitment found", http.StatusNotFound)
1✔
955
                return
1✔
956
        } else if respondwith.ErrorText(w, err) {
4✔
957
                return
×
958
        }
×
959

960
        var loc core.AZResourceLocation
3✔
961
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
3✔
962
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
3✔
963
        if errors.Is(err, sql.ErrNoRows) {
3✔
964
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
965
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
966
                return
×
967
        } else if respondwith.ErrorText(w, err) {
3✔
968
                return
×
969
        }
×
970

971
        // get target service and AZ resource
972
        var (
3✔
973
                sourceResourceID   db.ProjectResourceID
3✔
974
                targetResourceID   db.ProjectResourceID
3✔
975
                targetAZResourceID db.ProjectAZResourceID
3✔
976
        )
3✔
977
        err = p.DB.QueryRow(findTargetAZResourceIDBySourceIDQuery, dbCommitment.AZResourceID, targetProject.ID).
3✔
978
                Scan(&sourceResourceID, &targetResourceID, &targetAZResourceID)
3✔
979
        if respondwith.ErrorText(w, err) {
3✔
980
                return
×
981
        }
×
982

983
        // validate that we have enough committable capacity on the receiving side
984
        tx, err := p.DB.Begin()
3✔
985
        if respondwith.ErrorText(w, err) {
3✔
986
                return
×
987
        }
×
988
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
989
        ok, err := datamodel.CanMoveExistingCommitment(dbCommitment.Amount, loc, sourceResourceID, targetResourceID, p.Cluster, tx)
3✔
990
        if respondwith.ErrorText(w, err) {
3✔
991
                return
×
992
        }
×
993
        if !ok {
4✔
994
                http.Error(w, "not enough committable capacity on the receiving side", http.StatusConflict)
1✔
995
                return
1✔
996
        }
1✔
997

998
        dbCommitment.TransferStatus = ""
2✔
999
        dbCommitment.TransferToken = nil
2✔
1000
        dbCommitment.AZResourceID = targetAZResourceID
2✔
1001
        _, err = tx.Update(&dbCommitment)
2✔
1002
        if respondwith.ErrorText(w, err) {
2✔
1003
                return
×
1004
        }
×
1005
        err = tx.Commit()
2✔
1006
        if respondwith.ErrorText(w, err) {
2✔
1007
                return
×
1008
        }
×
1009

1010
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
2✔
1011
        p.auditor.Record(audittools.Event{
2✔
1012
                Time:       p.timeNow(),
2✔
1013
                Request:    r,
2✔
1014
                User:       token,
2✔
1015
                ReasonCode: http.StatusAccepted,
2✔
1016
                Action:     cadf.UpdateAction,
2✔
1017
                Target: commitmentEventTarget{
2✔
1018
                        DomainID:    dbDomain.UUID,
2✔
1019
                        DomainName:  dbDomain.Name,
2✔
1020
                        ProjectID:   targetProject.UUID,
2✔
1021
                        ProjectName: targetProject.Name,
2✔
1022
                        Commitments: []limesresources.Commitment{c},
2✔
1023
                },
2✔
1024
        })
2✔
1025

2✔
1026
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1027
}
1028

1029
// GetCommitmentConversion handles GET /v1/commitment-conversion/{service_type}/{resource_name}
1030
func (p *v1Provider) GetCommitmentConversions(w http.ResponseWriter, r *http.Request) {
2✔
1031
        httpapi.IdentifyEndpoint(r, "/v1/commitment-conversion/:service_type/:resource_name")
2✔
1032
        token := p.CheckToken(r)
2✔
1033
        if !token.Require(w, "cluster:show_basic") {
2✔
1034
                return
×
1035
        }
×
1036

1037
        // validate request
1038
        vars := mux.Vars(r)
2✔
1039
        nm := core.BuildResourceNameMapping(p.Cluster)
2✔
1040
        sourceServiceType, sourceResourceName, exists := nm.MapFromV1API(
2✔
1041
                limes.ServiceType(vars["service_type"]),
2✔
1042
                limesresources.ResourceName(vars["resource_name"]),
2✔
1043
        )
2✔
1044
        if !exists {
2✔
1045
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", vars["service_type"], vars["resource_name"])
×
1046
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1047
                return
×
1048
        }
×
1049
        sourceBehavior := p.Cluster.BehaviorForResource(sourceServiceType, sourceResourceName)
2✔
1050
        sourceResInfo := p.Cluster.InfoForResource(sourceServiceType, sourceResourceName)
2✔
1051

2✔
1052
        // enumerate possible conversions
2✔
1053
        conversions := make([]limesresources.CommitmentConversionRule, 0)
2✔
1054
        for targetServiceType, quotaPlugin := range p.Cluster.QuotaPlugins {
8✔
1055
                for targetResourceName, targetResInfo := range quotaPlugin.Resources() {
28✔
1056
                        targetBehavior := p.Cluster.BehaviorForResource(targetServiceType, targetResourceName)
22✔
1057
                        if targetBehavior.CommitmentConversion == (core.CommitmentConversion{}) {
30✔
1058
                                continue
8✔
1059
                        }
1060
                        if sourceServiceType == targetServiceType && sourceResourceName == targetResourceName {
16✔
1061
                                continue
2✔
1062
                        }
1063
                        if sourceResInfo.Unit != targetResInfo.Unit {
19✔
1064
                                continue
7✔
1065
                        }
1066
                        if sourceBehavior.CommitmentConversion.Identifier != targetBehavior.CommitmentConversion.Identifier {
6✔
1067
                                continue
1✔
1068
                        }
1069

1070
                        fromAmount, toAmount := p.getCommitmentConversionRate(sourceBehavior, targetBehavior)
4✔
1071
                        apiServiceType, apiResourceName, ok := nm.MapToV1API(targetServiceType, targetResourceName)
4✔
1072
                        if ok {
8✔
1073
                                conversions = append(conversions, limesresources.CommitmentConversionRule{
4✔
1074
                                        FromAmount:     fromAmount,
4✔
1075
                                        ToAmount:       toAmount,
4✔
1076
                                        TargetService:  apiServiceType,
4✔
1077
                                        TargetResource: apiResourceName,
4✔
1078
                                })
4✔
1079
                        }
4✔
1080
                }
1081
        }
1082

1083
        // use a defined sorting to ensure deterministic behavior in tests
1084
        slices.SortFunc(conversions, func(lhs, rhs limesresources.CommitmentConversionRule) int {
8✔
1085
                result := strings.Compare(string(lhs.TargetService), string(rhs.TargetService))
6✔
1086
                if result != 0 {
11✔
1087
                        return result
5✔
1088
                }
5✔
1089
                return strings.Compare(string(lhs.TargetResource), string(rhs.TargetResource))
1✔
1090
        })
1091

1092
        respondwith.JSON(w, http.StatusOK, map[string]any{"conversions": conversions})
2✔
1093
}
1094

1095
// ConvertCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/convert
1096
func (p *v1Provider) ConvertCommitment(w http.ResponseWriter, r *http.Request) {
9✔
1097
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/convert")
9✔
1098
        token := p.CheckToken(r)
9✔
1099
        if !token.Require(w, "project:edit") {
9✔
1100
                return
×
1101
        }
×
1102
        commitmentID := mux.Vars(r)["commitment_id"]
9✔
1103
        if commitmentID == "" {
9✔
1104
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1105
                return
×
1106
        }
×
1107
        dbDomain := p.FindDomainFromRequest(w, r)
9✔
1108
        if dbDomain == nil {
9✔
1109
                return
×
1110
        }
×
1111
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
9✔
1112
        if dbProject == nil {
9✔
1113
                return
×
1114
        }
×
1115

1116
        // section: sourceBehavior
1117
        var dbCommitment db.ProjectCommitment
9✔
1118
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
9✔
1119
        if errors.Is(err, sql.ErrNoRows) {
10✔
1120
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
1121
                return
1✔
1122
        } else if respondwith.ErrorText(w, err) {
9✔
1123
                return
×
1124
        }
×
1125
        var sourceLoc core.AZResourceLocation
8✔
1126
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
8✔
1127
                Scan(&sourceLoc.ServiceType, &sourceLoc.ResourceName, &sourceLoc.AvailabilityZone)
8✔
1128
        if errors.Is(err, sql.ErrNoRows) {
8✔
1129
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1130
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1131
                return
×
1132
        } else if respondwith.ErrorText(w, err) {
8✔
1133
                return
×
1134
        }
×
1135
        sourceBehavior := p.Cluster.BehaviorForResource(sourceLoc.ServiceType, sourceLoc.ResourceName)
8✔
1136

8✔
1137
        // section: targetBehavior
8✔
1138
        var parseTarget struct {
8✔
1139
                Request struct {
8✔
1140
                        TargetService  limes.ServiceType           `json:"target_service"`
8✔
1141
                        TargetResource limesresources.ResourceName `json:"target_resource"`
8✔
1142
                        SourceAmount   uint64                      `json:"source_amount"`
8✔
1143
                        TargetAmount   uint64                      `json:"target_amount"`
8✔
1144
                } `json:"commitment"`
8✔
1145
        }
8✔
1146
        if !RequireJSON(w, r, &parseTarget) {
8✔
1147
                return
×
1148
        }
×
1149
        req := parseTarget.Request
8✔
1150
        nm := core.BuildResourceNameMapping(p.Cluster)
8✔
1151
        targetServiceType, targetResourceName, exists := nm.MapFromV1API(req.TargetService, req.TargetResource)
8✔
1152
        if !exists {
8✔
1153
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", req.TargetService, req.TargetResource)
×
1154
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1155
                return
×
1156
        }
×
1157
        targetBehavior := p.Cluster.BehaviorForResource(targetServiceType, targetResourceName)
8✔
1158
        if sourceLoc.ResourceName == targetResourceName && sourceLoc.ServiceType == targetServiceType {
9✔
1159
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
1✔
1160
                return
1✔
1161
        }
1✔
1162
        if len(targetBehavior.CommitmentDurations) == 0 {
7✔
1163
                msg := fmt.Sprintf("commitments are not enabled for resource %s/%s", req.TargetService, req.TargetResource)
×
1164
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1165
                return
×
1166
        }
×
1167
        if sourceBehavior.CommitmentConversion.Identifier == "" || sourceBehavior.CommitmentConversion.Identifier != targetBehavior.CommitmentConversion.Identifier {
8✔
1168
                msg := fmt.Sprintf("commitment is not convertible into resource %s/%s", req.TargetService, req.TargetResource)
1✔
1169
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1170
                return
1✔
1171
        }
1✔
1172

1173
        // section: conversion
1174
        if req.SourceAmount > dbCommitment.Amount {
6✔
1175
                msg := fmt.Sprintf("unprocessable source amount. provided: %v, commitment: %v", req.SourceAmount, dbCommitment.Amount)
×
1176
                http.Error(w, msg, http.StatusConflict)
×
1177
                return
×
1178
        }
×
1179
        fromAmount, toAmount := p.getCommitmentConversionRate(sourceBehavior, targetBehavior)
6✔
1180
        conversionAmount := (req.SourceAmount / fromAmount) * toAmount
6✔
1181
        remainderAmount := req.SourceAmount % fromAmount
6✔
1182
        if remainderAmount > 0 {
8✔
1183
                msg := fmt.Sprintf("amount: %v does not fit into conversion rate of: %v", req.SourceAmount, fromAmount)
2✔
1184
                http.Error(w, msg, http.StatusConflict)
2✔
1185
                return
2✔
1186
        }
2✔
1187
        if conversionAmount != req.TargetAmount {
5✔
1188
                msg := fmt.Sprintf("conversion mismatch. provided: %v, calculated: %v", req.TargetAmount, conversionAmount)
1✔
1189
                http.Error(w, msg, http.StatusConflict)
1✔
1190
                return
1✔
1191
        }
1✔
1192

1193
        tx, err := p.DB.Begin()
3✔
1194
        if respondwith.ErrorText(w, err) {
3✔
1195
                return
×
1196
        }
×
1197
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1198

3✔
1199
        var (
3✔
1200
                targetResourceID   db.ProjectResourceID
3✔
1201
                targetAZResourceID db.ProjectAZResourceID
3✔
1202
        )
3✔
1203
        err = p.DB.QueryRow(findTargetAZResourceByTargetProjectQuery, dbProject.ID, targetServiceType, targetResourceName, sourceLoc.AvailabilityZone).
3✔
1204
                Scan(&targetResourceID, &targetAZResourceID)
3✔
1205
        if respondwith.ErrorText(w, err) {
3✔
1206
                return
×
1207
        }
×
1208
        // defense in depth. ServiceType and ResourceName of source and target are already checked. Here it's possible to explicitly check the ID's.
1209
        if dbCommitment.AZResourceID == targetAZResourceID {
3✔
1210
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
×
1211
                return
×
1212
        }
×
1213
        targetLoc := core.AZResourceLocation{
3✔
1214
                ServiceType:      targetServiceType,
3✔
1215
                ResourceName:     targetResourceName,
3✔
1216
                AvailabilityZone: sourceLoc.AvailabilityZone,
3✔
1217
        }
3✔
1218
        // The commitment at the source resource was already confirmed and checked.
3✔
1219
        // Therefore only the addition to the target resource has to be checked against.
3✔
1220
        if dbCommitment.ConfirmedAt != nil {
5✔
1221
                ok, err := datamodel.CanConfirmNewCommitment(targetLoc, targetResourceID, conversionAmount, p.Cluster, p.DB)
2✔
1222
                if respondwith.ErrorText(w, err) {
2✔
1223
                        return
×
1224
                }
×
1225
                if !ok {
3✔
1226
                        http.Error(w, "not enough capacity to confirm the commitment", http.StatusUnprocessableEntity)
1✔
1227
                        return
1✔
1228
                }
1✔
1229
        }
1230

1231
        auditEvent := commitmentEventTarget{
2✔
1232
                DomainID:    dbDomain.UUID,
2✔
1233
                DomainName:  dbDomain.Name,
2✔
1234
                ProjectID:   dbProject.UUID,
2✔
1235
                ProjectName: dbProject.Name,
2✔
1236
        }
2✔
1237

2✔
1238
        relatedCommitmentIDs := make([]db.ProjectCommitmentID, 0)
2✔
1239
        remainingAmount := dbCommitment.Amount - req.SourceAmount
2✔
1240
        if remainingAmount > 0 {
3✔
1241
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
1✔
1242
                if respondwith.ErrorText(w, err) {
1✔
NEW
1243
                        return
×
NEW
1244
                }
×
1245
                relatedCommitmentIDs = append(relatedCommitmentIDs, remainingCommitment.ID)
1✔
1246
                err = tx.Insert(&remainingCommitment)
1✔
1247
                if respondwith.ErrorText(w, err) {
1✔
1248
                        return
×
1249
                }
×
1250
                auditEvent.Commitments = append(auditEvent.Commitments,
1✔
1251
                        p.convertCommitmentToDisplayForm(remainingCommitment, sourceLoc, token),
1✔
1252
                )
1✔
1253
        }
1254

1255
        convertedCommitment, err := p.buildConvertedCommitment(dbCommitment, targetAZResourceID, conversionAmount)
2✔
1256
        if respondwith.ErrorText(w, err) {
2✔
NEW
1257
                return
×
NEW
1258
        }
×
1259
        relatedCommitmentIDs = append(relatedCommitmentIDs, convertedCommitment.ID)
2✔
1260
        err = tx.Insert(&convertedCommitment)
2✔
1261
        if respondwith.ErrorText(w, err) {
2✔
1262
                return
×
1263
        }
×
1264

1265
        // supersede the original commitment
1266
        now := p.timeNow()
2✔
1267
        supersedeContext := db.CommitmentWorkflowContext{
2✔
1268
                Reason:               db.CommitmentReasonConvert,
2✔
1269
                RelatedCommitmentIDs: relatedCommitmentIDs,
2✔
1270
        }
2✔
1271
        buf, err := json.Marshal(supersedeContext)
2✔
1272
        if respondwith.ErrorText(w, err) {
2✔
NEW
1273
                return
×
NEW
1274
        }
×
1275
        dbCommitment.State = db.CommitmentStateSuperseded
2✔
1276
        dbCommitment.SupersededAt = &now
2✔
1277
        dbCommitment.SupersedeContextJSON = liquids.PointerTo(json.RawMessage(buf))
2✔
1278
        _, err = tx.Update(&dbCommitment)
2✔
1279
        if respondwith.ErrorText(w, err) {
2✔
1280
                return
×
1281
        }
×
1282

1283
        err = tx.Commit()
2✔
1284
        if respondwith.ErrorText(w, err) {
2✔
1285
                return
×
1286
        }
×
1287

1288
        c := p.convertCommitmentToDisplayForm(convertedCommitment, targetLoc, token)
2✔
1289
        auditEvent.Commitments = append([]limesresources.Commitment{c}, auditEvent.Commitments...)
2✔
1290
        auditEvent.WorkflowContext = &db.CommitmentWorkflowContext{
2✔
1291
                Reason:               db.CommitmentReasonSplit,
2✔
1292
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1293
        }
2✔
1294
        p.auditor.Record(audittools.Event{
2✔
1295
                Time:       p.timeNow(),
2✔
1296
                Request:    r,
2✔
1297
                User:       token,
2✔
1298
                ReasonCode: http.StatusAccepted,
2✔
1299
                Action:     cadf.UpdateAction,
2✔
1300
                Target:     auditEvent,
2✔
1301
        })
2✔
1302

2✔
1303
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1304
}
1305

1306
func (p *v1Provider) getCommitmentConversionRate(source, target core.ResourceBehavior) (fromAmount, toAmount uint64) {
10✔
1307
        divisor := GetGreatestCommonDivisor(source.CommitmentConversion.Weight, target.CommitmentConversion.Weight)
10✔
1308
        fromAmount = target.CommitmentConversion.Weight / divisor
10✔
1309
        toAmount = source.CommitmentConversion.Weight / divisor
10✔
1310
        return fromAmount, toAmount
10✔
1311
}
10✔
1312

1313
// ExtendCommitmentDuration handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/update-duration
1314
func (p *v1Provider) UpdateCommitmentDuration(w http.ResponseWriter, r *http.Request) {
6✔
1315
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/update-duration")
6✔
1316
        token := p.CheckToken(r)
6✔
1317
        if !token.Require(w, "project:edit") {
6✔
1318
                return
×
1319
        }
×
1320
        commitmentID := mux.Vars(r)["commitment_id"]
6✔
1321
        if commitmentID == "" {
6✔
1322
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1323
                return
×
1324
        }
×
1325
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
1326
        if dbDomain == nil {
6✔
1327
                return
×
1328
        }
×
1329
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
1330
        if dbProject == nil {
6✔
1331
                return
×
1332
        }
×
1333
        var Request struct {
6✔
1334
                Duration limesresources.CommitmentDuration `json:"duration"`
6✔
1335
        }
6✔
1336
        req := Request
6✔
1337
        if !RequireJSON(w, r, &req) {
6✔
1338
                return
×
1339
        }
×
1340

1341
        var dbCommitment db.ProjectCommitment
6✔
1342
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
6✔
1343
        if errors.Is(err, sql.ErrNoRows) {
6✔
1344
                http.Error(w, "no such commitment", http.StatusNotFound)
×
1345
                return
×
1346
        } else if respondwith.ErrorText(w, err) {
6✔
1347
                return
×
1348
        }
×
1349

1350
        now := p.timeNow()
6✔
1351
        if dbCommitment.ExpiresAt.Before(now) || dbCommitment.ExpiresAt.Equal(now) {
7✔
1352
                http.Error(w, "unable to process expired commitment", http.StatusForbidden)
1✔
1353
                return
1✔
1354
        }
1✔
1355

1356
        if dbCommitment.State == db.CommitmentStateSuperseded {
6✔
1357
                msg := fmt.Sprintf("unable to operate on commitment with a state of %s", dbCommitment.State)
1✔
1358
                http.Error(w, msg, http.StatusForbidden)
1✔
1359
                return
1✔
1360
        }
1✔
1361

1362
        var loc core.AZResourceLocation
4✔
1363
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
4✔
1364
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
4✔
1365
        if errors.Is(err, sql.ErrNoRows) {
4✔
1366
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1367
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1368
                return
×
1369
        } else if respondwith.ErrorText(w, err) {
4✔
1370
                return
×
1371
        }
×
1372
        behavior := p.Cluster.BehaviorForResource(loc.ServiceType, loc.ResourceName)
4✔
1373
        if !slices.Contains(behavior.CommitmentDurations, req.Duration) {
5✔
1374
                msg := fmt.Sprintf("provided duration: %s does not match the config %v", req.Duration, behavior.CommitmentDurations)
1✔
1375
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1376
                return
1✔
1377
        }
1✔
1378

1379
        newExpiresAt := req.Duration.AddTo(unwrapOrDefault(dbCommitment.ConfirmBy, dbCommitment.CreatedAt))
3✔
1380
        if newExpiresAt.Before(dbCommitment.ExpiresAt) {
4✔
1381
                msg := fmt.Sprintf("duration change from %s to %s forbidden", dbCommitment.Duration, req.Duration)
1✔
1382
                http.Error(w, msg, http.StatusForbidden)
1✔
1383
                return
1✔
1384
        }
1✔
1385

1386
        dbCommitment.Duration = req.Duration
2✔
1387
        dbCommitment.ExpiresAt = newExpiresAt
2✔
1388
        _, err = p.DB.Update(&dbCommitment)
2✔
1389
        if respondwith.ErrorText(w, err) {
2✔
1390
                return
×
1391
        }
×
1392

1393
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
2✔
1394
        p.auditor.Record(audittools.Event{
2✔
1395
                Time:       p.timeNow(),
2✔
1396
                Request:    r,
2✔
1397
                User:       token,
2✔
1398
                ReasonCode: http.StatusOK,
2✔
1399
                Action:     cadf.UpdateAction,
2✔
1400
                Target: commitmentEventTarget{
2✔
1401
                        DomainID:    dbDomain.UUID,
2✔
1402
                        DomainName:  dbDomain.Name,
2✔
1403
                        ProjectID:   dbProject.UUID,
2✔
1404
                        ProjectName: dbProject.Name,
2✔
1405
                        Commitments: []limesresources.Commitment{c},
2✔
1406
                },
2✔
1407
        })
2✔
1408

2✔
1409
        respondwith.JSON(w, http.StatusOK, map[string]any{"commitment": c})
2✔
1410
}
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