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

sapcc / limes / 13410079397

19 Feb 2025 10:08AM UTC coverage: 79.641% (+0.01%) from 79.629%
13410079397

Pull #661

github

Varsius
add api endpoint for commitment merging
Pull Request #661: add api endpoint for commitment merging

188 of 224 new or added lines in 5 files covered. (83.93%)

119 existing lines in 2 files now uncovered.

5723 of 7186 relevant lines covered (79.64%)

61.62 hits per line

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

79.15
/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]datamodel.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 datamodel.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 datamodel.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, *datamodel.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 := datamodel.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.CommitmenReasonCreate}
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
                CreationContext: liquids.PointerTo(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
                },
21✔
439
        })
21✔
440

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

679
func (p *v1Provider) canDeleteCommitment(token *gopherpolicy.Token, commitment db.ProjectCommitment) bool {
80✔
680
        // up to 24 hours after creation of fresh commitments, future commitments can still be deleted by their creators
80✔
681
        if commitment.State == db.CommitmentStatePlanned || commitment.State == db.CommitmentStatePending || commitment.State == db.CommitmentStateActive {
160✔
682
                if p.timeNow().Before(commitment.CreatedAt.Add(24 * time.Hour)) {
146✔
683
                        if token.Check("project:edit") {
132✔
684
                                return true
66✔
685
                        }
66✔
686
                }
687
        }
688

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

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

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

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

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

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

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

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

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

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

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

863
func (p *v1Provider) buildConvertedCommitment(dbCommitment db.ProjectCommitment, azResourceID db.ProjectAZResourceID, amount uint64) (db.ProjectCommitment, error) {
2✔
864
        commitment, err := p.buildSplitCommitment(dbCommitment, amount)
2✔
865
        commitment.AZResourceID = azResourceID
2✔
866
        return commitment, err
2✔
867
}
2✔
868

869
// GetCommitmentByTransferToken handles GET /v1/commitments/{token}
870
func (p *v1Provider) GetCommitmentByTransferToken(w http.ResponseWriter, r *http.Request) {
2✔
871
        httpapi.IdentifyEndpoint(r, "/v1/commitments/:token")
2✔
872
        token := p.CheckToken(r)
2✔
873
        if !token.Require(w, "cluster:show_basic") {
2✔
874
                return
×
875
        }
×
876
        transferToken := mux.Vars(r)["token"]
2✔
877

2✔
878
        // The token column is a unique key, so we expect only one result.
2✔
879
        var dbCommitment db.ProjectCommitment
2✔
880
        err := p.DB.SelectOne(&dbCommitment, findCommitmentByTransferToken, transferToken)
2✔
881
        if errors.Is(err, sql.ErrNoRows) {
3✔
882
                http.Error(w, "no matching commitment found.", http.StatusNotFound)
1✔
883
                return
1✔
884
        } else if respondwith.ErrorText(w, err) {
2✔
885
                return
×
886
        }
×
887

888
        var loc datamodel.AZResourceLocation
1✔
889
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
1✔
890
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
1✔
891
        if errors.Is(err, sql.ErrNoRows) {
1✔
UNCOV
892
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
UNCOV
893
                http.Error(w, "location data not found.", http.StatusNotFound)
×
UNCOV
894
                return
×
895
        } else if respondwith.ErrorText(w, err) {
1✔
896
                return
×
UNCOV
897
        }
×
898

899
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
1✔
900
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
901
}
902

903
// TransferCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/transfer-commitment/{id}?token={token}
904
func (p *v1Provider) TransferCommitment(w http.ResponseWriter, r *http.Request) {
5✔
905
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/transfer-commitment/:id")
5✔
906
        token := p.CheckToken(r)
5✔
907
        if !token.Require(w, "project:edit") {
5✔
UNCOV
908
                return
×
UNCOV
909
        }
×
910
        transferToken := r.Header.Get("Transfer-Token")
5✔
911
        if transferToken == "" {
6✔
912
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
1✔
913
                return
1✔
914
        }
1✔
915
        commitmentID := mux.Vars(r)["id"]
4✔
916
        if commitmentID == "" {
4✔
917
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
918
                return
×
UNCOV
919
        }
×
920
        dbDomain := p.FindDomainFromRequest(w, r)
4✔
921
        if dbDomain == nil {
4✔
UNCOV
922
                return
×
UNCOV
923
        }
×
924
        targetProject := p.FindProjectFromRequest(w, r, dbDomain)
4✔
925
        if targetProject == nil {
4✔
UNCOV
926
                return
×
UNCOV
927
        }
×
928

929
        // find commitment by transfer_token
930
        var dbCommitment db.ProjectCommitment
4✔
931
        err := p.DB.SelectOne(&dbCommitment, getCommitmentWithMatchingTransferTokenQuery, commitmentID, transferToken)
4✔
932
        if errors.Is(err, sql.ErrNoRows) {
5✔
933
                http.Error(w, "no matching commitment found", http.StatusNotFound)
1✔
934
                return
1✔
935
        } else if respondwith.ErrorText(w, err) {
4✔
UNCOV
936
                return
×
UNCOV
937
        }
×
938

939
        var loc datamodel.AZResourceLocation
3✔
940
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
3✔
941
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
3✔
942
        if errors.Is(err, sql.ErrNoRows) {
3✔
943
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
944
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
UNCOV
945
                return
×
946
        } else if respondwith.ErrorText(w, err) {
3✔
947
                return
×
948
        }
×
949

950
        // get target service and AZ resource
951
        var (
3✔
952
                sourceResourceID   db.ProjectResourceID
3✔
953
                targetResourceID   db.ProjectResourceID
3✔
954
                targetAZResourceID db.ProjectAZResourceID
3✔
955
        )
3✔
956
        err = p.DB.QueryRow(findTargetAZResourceIDBySourceIDQuery, dbCommitment.AZResourceID, targetProject.ID).
3✔
957
                Scan(&sourceResourceID, &targetResourceID, &targetAZResourceID)
3✔
958
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
959
                return
×
UNCOV
960
        }
×
961

962
        // validate that we have enough committable capacity on the receiving side
963
        tx, err := p.DB.Begin()
3✔
964
        if respondwith.ErrorText(w, err) {
3✔
965
                return
×
966
        }
×
967
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
968
        ok, err := datamodel.CanMoveExistingCommitment(dbCommitment.Amount, loc, sourceResourceID, targetResourceID, p.Cluster, tx)
3✔
969
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
970
                return
×
UNCOV
971
        }
×
972
        if !ok {
4✔
973
                http.Error(w, "not enough committable capacity on the receiving side", http.StatusConflict)
1✔
974
                return
1✔
975
        }
1✔
976

977
        dbCommitment.TransferStatus = ""
2✔
978
        dbCommitment.TransferToken = nil
2✔
979
        dbCommitment.AZResourceID = targetAZResourceID
2✔
980
        _, err = tx.Update(&dbCommitment)
2✔
981
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
982
                return
×
UNCOV
983
        }
×
984
        err = tx.Commit()
2✔
985
        if respondwith.ErrorText(w, err) {
2✔
986
                return
×
987
        }
×
988

989
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
2✔
990
        p.auditor.Record(audittools.Event{
2✔
991
                Time:       p.timeNow(),
2✔
992
                Request:    r,
2✔
993
                User:       token,
2✔
994
                ReasonCode: http.StatusAccepted,
2✔
995
                Action:     cadf.UpdateAction,
2✔
996
                Target: commitmentEventTarget{
2✔
997
                        DomainID:    dbDomain.UUID,
2✔
998
                        DomainName:  dbDomain.Name,
2✔
999
                        ProjectID:   targetProject.UUID,
2✔
1000
                        ProjectName: targetProject.Name,
2✔
1001
                        Commitments: []limesresources.Commitment{c},
2✔
1002
                },
2✔
1003
        })
2✔
1004

2✔
1005
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1006
}
1007

1008
// GetCommitmentConversion handles GET /v1/commitment-conversion/{service_type}/{resource_name}
1009
func (p *v1Provider) GetCommitmentConversions(w http.ResponseWriter, r *http.Request) {
2✔
1010
        httpapi.IdentifyEndpoint(r, "/v1/commitment-conversion/:service_type/:resource_name")
2✔
1011
        token := p.CheckToken(r)
2✔
1012
        if !token.Require(w, "cluster:show_basic") {
2✔
UNCOV
1013
                return
×
UNCOV
1014
        }
×
1015

1016
        // validate request
1017
        vars := mux.Vars(r)
2✔
1018
        nm := core.BuildResourceNameMapping(p.Cluster)
2✔
1019
        sourceServiceType, sourceResourceName, exists := nm.MapFromV1API(
2✔
1020
                limes.ServiceType(vars["service_type"]),
2✔
1021
                limesresources.ResourceName(vars["resource_name"]),
2✔
1022
        )
2✔
1023
        if !exists {
2✔
UNCOV
1024
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", vars["service_type"], vars["resource_name"])
×
UNCOV
1025
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
UNCOV
1026
                return
×
UNCOV
1027
        }
×
1028
        sourceBehavior := p.Cluster.BehaviorForResource(sourceServiceType, sourceResourceName)
2✔
1029
        sourceResInfo := p.Cluster.InfoForResource(sourceServiceType, sourceResourceName)
2✔
1030

2✔
1031
        // enumerate possible conversions
2✔
1032
        conversions := make([]limesresources.CommitmentConversionRule, 0)
2✔
1033
        for targetServiceType, quotaPlugin := range p.Cluster.QuotaPlugins {
8✔
1034
                for targetResourceName, targetResInfo := range quotaPlugin.Resources() {
28✔
1035
                        targetBehavior := p.Cluster.BehaviorForResource(targetServiceType, targetResourceName)
22✔
1036
                        if targetBehavior.CommitmentConversion == (core.CommitmentConversion{}) {
30✔
1037
                                continue
8✔
1038
                        }
1039
                        if sourceServiceType == targetServiceType && sourceResourceName == targetResourceName {
16✔
1040
                                continue
2✔
1041
                        }
1042
                        if sourceResInfo.Unit != targetResInfo.Unit {
19✔
1043
                                continue
7✔
1044
                        }
1045
                        if sourceBehavior.CommitmentConversion.Identifier != targetBehavior.CommitmentConversion.Identifier {
6✔
1046
                                continue
1✔
1047
                        }
1048

1049
                        fromAmount, toAmount := p.getCommitmentConversionRate(sourceBehavior, targetBehavior)
4✔
1050
                        apiServiceType, apiResourceName, ok := nm.MapToV1API(targetServiceType, targetResourceName)
4✔
1051
                        if ok {
8✔
1052
                                conversions = append(conversions, limesresources.CommitmentConversionRule{
4✔
1053
                                        FromAmount:     fromAmount,
4✔
1054
                                        ToAmount:       toAmount,
4✔
1055
                                        TargetService:  apiServiceType,
4✔
1056
                                        TargetResource: apiResourceName,
4✔
1057
                                })
4✔
1058
                        }
4✔
1059
                }
1060
        }
1061

1062
        // use a defined sorting to ensure deterministic behavior in tests
1063
        slices.SortFunc(conversions, func(lhs, rhs limesresources.CommitmentConversionRule) int {
5✔
1064
                result := strings.Compare(string(lhs.TargetService), string(rhs.TargetService))
3✔
1065
                if result != 0 {
5✔
1066
                        return result
2✔
1067
                }
2✔
1068
                return strings.Compare(string(lhs.TargetResource), string(rhs.TargetResource))
1✔
1069
        })
1070

1071
        respondwith.JSON(w, http.StatusOK, map[string]any{"conversions": conversions})
2✔
1072
}
1073

1074
// ConvertCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/convert
1075
func (p *v1Provider) ConvertCommitment(w http.ResponseWriter, r *http.Request) {
9✔
1076
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/convert")
9✔
1077
        token := p.CheckToken(r)
9✔
1078
        if !token.Require(w, "project:edit") {
9✔
UNCOV
1079
                return
×
UNCOV
1080
        }
×
1081
        commitmentID := mux.Vars(r)["commitment_id"]
9✔
1082
        if commitmentID == "" {
9✔
UNCOV
1083
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
UNCOV
1084
                return
×
UNCOV
1085
        }
×
1086
        dbDomain := p.FindDomainFromRequest(w, r)
9✔
1087
        if dbDomain == nil {
9✔
UNCOV
1088
                return
×
UNCOV
1089
        }
×
1090
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
9✔
1091
        if dbProject == nil {
9✔
UNCOV
1092
                return
×
UNCOV
1093
        }
×
1094

1095
        // section: sourceBehavior
1096
        var dbCommitment db.ProjectCommitment
9✔
1097
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
9✔
1098
        if errors.Is(err, sql.ErrNoRows) {
10✔
1099
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
1100
                return
1✔
1101
        } else if respondwith.ErrorText(w, err) {
9✔
UNCOV
1102
                return
×
UNCOV
1103
        }
×
1104
        var sourceLoc datamodel.AZResourceLocation
8✔
1105
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
8✔
1106
                Scan(&sourceLoc.ServiceType, &sourceLoc.ResourceName, &sourceLoc.AvailabilityZone)
8✔
1107
        if errors.Is(err, sql.ErrNoRows) {
8✔
UNCOV
1108
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1109
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1110
                return
×
1111
        } else if respondwith.ErrorText(w, err) {
8✔
UNCOV
1112
                return
×
1113
        }
×
1114
        sourceBehavior := p.Cluster.BehaviorForResource(sourceLoc.ServiceType, sourceLoc.ResourceName)
8✔
1115

8✔
1116
        // section: targetBehavior
8✔
1117
        var parseTarget struct {
8✔
1118
                Request struct {
8✔
1119
                        TargetService  limes.ServiceType           `json:"target_service"`
8✔
1120
                        TargetResource limesresources.ResourceName `json:"target_resource"`
8✔
1121
                        SourceAmount   uint64                      `json:"source_amount"`
8✔
1122
                        TargetAmount   uint64                      `json:"target_amount"`
8✔
1123
                } `json:"commitment"`
8✔
1124
        }
8✔
1125
        if !RequireJSON(w, r, &parseTarget) {
8✔
UNCOV
1126
                return
×
UNCOV
1127
        }
×
1128
        req := parseTarget.Request
8✔
1129
        nm := core.BuildResourceNameMapping(p.Cluster)
8✔
1130
        targetServiceType, targetResourceName, exists := nm.MapFromV1API(req.TargetService, req.TargetResource)
8✔
1131
        if !exists {
8✔
UNCOV
1132
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", req.TargetService, req.TargetResource)
×
1133
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1134
                return
×
UNCOV
1135
        }
×
1136
        targetBehavior := p.Cluster.BehaviorForResource(targetServiceType, targetResourceName)
8✔
1137
        if sourceLoc.ResourceName == targetResourceName && sourceLoc.ServiceType == targetServiceType {
9✔
1138
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
1✔
1139
                return
1✔
1140
        }
1✔
1141
        if len(targetBehavior.CommitmentDurations) == 0 {
7✔
UNCOV
1142
                msg := fmt.Sprintf("commitments are not enabled for resource %s/%s", req.TargetService, req.TargetResource)
×
UNCOV
1143
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
UNCOV
1144
                return
×
UNCOV
1145
        }
×
1146
        if sourceBehavior.CommitmentConversion.Identifier == "" || sourceBehavior.CommitmentConversion.Identifier != targetBehavior.CommitmentConversion.Identifier {
8✔
1147
                msg := fmt.Sprintf("commitment is not convertible into resource %s/%s", req.TargetService, req.TargetResource)
1✔
1148
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1149
                return
1✔
1150
        }
1✔
1151

1152
        // section: conversion
1153
        if req.SourceAmount > dbCommitment.Amount {
6✔
1154
                msg := fmt.Sprintf("unprocessable source amount. provided: %v, commitment: %v", req.SourceAmount, dbCommitment.Amount)
×
1155
                http.Error(w, msg, http.StatusConflict)
×
1156
                return
×
UNCOV
1157
        }
×
1158
        fromAmount, toAmount := p.getCommitmentConversionRate(sourceBehavior, targetBehavior)
6✔
1159
        conversionAmount := (req.SourceAmount / fromAmount) * toAmount
6✔
1160
        remainderAmount := req.SourceAmount % fromAmount
6✔
1161
        if remainderAmount > 0 {
8✔
1162
                msg := fmt.Sprintf("amount: %v does not fit into conversion rate of: %v", req.SourceAmount, fromAmount)
2✔
1163
                http.Error(w, msg, http.StatusConflict)
2✔
1164
                return
2✔
1165
        }
2✔
1166
        if conversionAmount != req.TargetAmount {
5✔
1167
                msg := fmt.Sprintf("conversion mismatch. provided: %v, calculated: %v", req.TargetAmount, conversionAmount)
1✔
1168
                http.Error(w, msg, http.StatusConflict)
1✔
1169
                return
1✔
1170
        }
1✔
1171

1172
        tx, err := p.DB.Begin()
3✔
1173
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
1174
                return
×
1175
        }
×
1176
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1177

3✔
1178
        var (
3✔
1179
                targetResourceID   db.ProjectResourceID
3✔
1180
                targetAZResourceID db.ProjectAZResourceID
3✔
1181
        )
3✔
1182
        err = p.DB.QueryRow(findTargetAZResourceByTargetProjectQuery, dbProject.ID, targetServiceType, targetResourceName, sourceLoc.AvailabilityZone).
3✔
1183
                Scan(&targetResourceID, &targetAZResourceID)
3✔
1184
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
1185
                return
×
UNCOV
1186
        }
×
1187
        // defense in depth. ServiceType and ResourceName of source and target are already checked. Here it's possible to explicitly check the ID's.
1188
        if dbCommitment.AZResourceID == targetAZResourceID {
3✔
UNCOV
1189
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
×
UNCOV
1190
                return
×
UNCOV
1191
        }
×
1192
        targetLoc := datamodel.AZResourceLocation{
3✔
1193
                ServiceType:      targetServiceType,
3✔
1194
                ResourceName:     targetResourceName,
3✔
1195
                AvailabilityZone: sourceLoc.AvailabilityZone,
3✔
1196
        }
3✔
1197
        // The commitment at the source resource was already confirmed and checked.
3✔
1198
        // Therefore only the addition to the target resource has to be checked against.
3✔
1199
        if dbCommitment.ConfirmedAt != nil {
5✔
1200
                ok, err := datamodel.CanConfirmNewCommitment(targetLoc, targetResourceID, conversionAmount, p.Cluster, p.DB)
2✔
1201
                if respondwith.ErrorText(w, err) {
2✔
UNCOV
1202
                        return
×
UNCOV
1203
                }
×
1204
                if !ok {
3✔
1205
                        http.Error(w, "not enough capacity to confirm the commitment", http.StatusUnprocessableEntity)
1✔
1206
                        return
1✔
1207
                }
1✔
1208
        }
1209

1210
        auditEvent := commitmentEventTarget{
2✔
1211
                DomainID:    dbDomain.UUID,
2✔
1212
                DomainName:  dbDomain.Name,
2✔
1213
                ProjectID:   dbProject.UUID,
2✔
1214
                ProjectName: dbProject.Name,
2✔
1215
        }
2✔
1216

2✔
1217
        relatedCommitmentIDs := make([]db.ProjectCommitmentID, 0)
2✔
1218
        remainingAmount := dbCommitment.Amount - req.SourceAmount
2✔
1219
        if remainingAmount > 0 {
3✔
1220
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
1✔
1221
                if respondwith.ErrorText(w, err) {
1✔
NEW
UNCOV
1222
                        return
×
NEW
1223
                }
×
1224
                relatedCommitmentIDs = append(relatedCommitmentIDs, remainingCommitment.ID)
1✔
1225
                err = tx.Insert(&remainingCommitment)
1✔
1226
                if respondwith.ErrorText(w, err) {
1✔
UNCOV
1227
                        return
×
UNCOV
1228
                }
×
1229
                auditEvent.Commitments = append(auditEvent.Commitments,
1✔
1230
                        p.convertCommitmentToDisplayForm(remainingCommitment, sourceLoc, token),
1✔
1231
                )
1✔
1232
        }
1233

1234
        convertedCommitment, err := p.buildConvertedCommitment(dbCommitment, targetAZResourceID, conversionAmount)
2✔
1235
        if respondwith.ErrorText(w, err) {
2✔
NEW
UNCOV
1236
                return
×
NEW
UNCOV
1237
        }
×
1238
        relatedCommitmentIDs = append(relatedCommitmentIDs, convertedCommitment.ID)
2✔
1239
        err = tx.Insert(&convertedCommitment)
2✔
1240
        if respondwith.ErrorText(w, err) {
2✔
1241
                return
×
1242
        }
×
1243

1244
        // supersede the original commitment
1245
        now := p.timeNow()
2✔
1246
        supersedeContext := db.CommitmentWorkflowContext{
2✔
1247
                Reason:               db.CommitmenReasonConvert,
2✔
1248
                RelatedCommitmentIDs: relatedCommitmentIDs,
2✔
1249
        }
2✔
1250
        buf, err := json.Marshal(supersedeContext)
2✔
1251
        if respondwith.ErrorText(w, err) {
2✔
NEW
UNCOV
1252
                return
×
NEW
UNCOV
1253
        }
×
1254
        dbCommitment.State = db.CommitmentStateSuperseded
2✔
1255
        dbCommitment.SupersededAt = &now
2✔
1256
        dbCommitment.SupersedeContext = liquids.PointerTo(json.RawMessage(buf))
2✔
1257
        _, err = tx.Update(&dbCommitment)
2✔
1258
        if respondwith.ErrorText(w, err) {
2✔
1259
                return
×
UNCOV
1260
        }
×
1261

1262
        err = tx.Commit()
2✔
1263
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1264
                return
×
UNCOV
1265
        }
×
1266

1267
        c := p.convertCommitmentToDisplayForm(convertedCommitment, targetLoc, token)
2✔
1268
        auditEvent.Commitments = append([]limesresources.Commitment{c}, auditEvent.Commitments...)
2✔
1269
        auditEvent.WorkflowContext = &db.CommitmentWorkflowContext{
2✔
1270
                Reason:               db.CommitmenReasonSplit,
2✔
1271
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1272
        }
2✔
1273
        p.auditor.Record(audittools.Event{
2✔
1274
                Time:       p.timeNow(),
2✔
1275
                Request:    r,
2✔
1276
                User:       token,
2✔
1277
                ReasonCode: http.StatusAccepted,
2✔
1278
                Action:     cadf.UpdateAction,
2✔
1279
                Target:     auditEvent,
2✔
1280
        })
2✔
1281

2✔
1282
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1283
}
1284

1285
func (p *v1Provider) getCommitmentConversionRate(source, target core.ResourceBehavior) (fromAmount, toAmount uint64) {
10✔
1286
        divisor := GetGreatestCommonDivisor(source.CommitmentConversion.Weight, target.CommitmentConversion.Weight)
10✔
1287
        fromAmount = target.CommitmentConversion.Weight / divisor
10✔
1288
        toAmount = source.CommitmentConversion.Weight / divisor
10✔
1289
        return fromAmount, toAmount
10✔
1290
}
10✔
1291

1292
// ExtendCommitmentDuration handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/update-duration
1293
func (p *v1Provider) UpdateCommitmentDuration(w http.ResponseWriter, r *http.Request) {
6✔
1294
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/update-duration")
6✔
1295
        token := p.CheckToken(r)
6✔
1296
        if !token.Require(w, "project:edit") {
6✔
UNCOV
1297
                return
×
UNCOV
1298
        }
×
1299
        commitmentID := mux.Vars(r)["commitment_id"]
6✔
1300
        if commitmentID == "" {
6✔
UNCOV
1301
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
UNCOV
1302
                return
×
UNCOV
1303
        }
×
1304
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
1305
        if dbDomain == nil {
6✔
UNCOV
1306
                return
×
UNCOV
1307
        }
×
1308
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
1309
        if dbProject == nil {
6✔
UNCOV
1310
                return
×
UNCOV
1311
        }
×
1312
        var Request struct {
6✔
1313
                Duration limesresources.CommitmentDuration `json:"duration"`
6✔
1314
        }
6✔
1315
        req := Request
6✔
1316
        if !RequireJSON(w, r, &req) {
6✔
UNCOV
1317
                return
×
1318
        }
×
1319

1320
        var dbCommitment db.ProjectCommitment
6✔
1321
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
6✔
1322
        if errors.Is(err, sql.ErrNoRows) {
6✔
1323
                http.Error(w, "no such commitment", http.StatusNotFound)
×
1324
                return
×
1325
        } else if respondwith.ErrorText(w, err) {
6✔
UNCOV
1326
                return
×
1327
        }
×
1328

1329
        now := p.timeNow()
6✔
1330
        if dbCommitment.ExpiresAt.Before(now) || dbCommitment.ExpiresAt.Equal(now) {
7✔
1331
                http.Error(w, "unable to process expired commitment", http.StatusForbidden)
1✔
1332
                return
1✔
1333
        }
1✔
1334

1335
        if dbCommitment.State == db.CommitmentStateSuperseded {
6✔
1336
                msg := fmt.Sprintf("unable to operate on commitment with a state of %s", dbCommitment.State)
1✔
1337
                http.Error(w, msg, http.StatusForbidden)
1✔
1338
                return
1✔
1339
        }
1✔
1340

1341
        var loc datamodel.AZResourceLocation
4✔
1342
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
4✔
1343
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
4✔
1344
        if errors.Is(err, sql.ErrNoRows) {
4✔
1345
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
UNCOV
1346
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1347
                return
×
1348
        } else if respondwith.ErrorText(w, err) {
4✔
UNCOV
1349
                return
×
UNCOV
1350
        }
×
1351
        behavior := p.Cluster.BehaviorForResource(loc.ServiceType, loc.ResourceName)
4✔
1352
        if !slices.Contains(behavior.CommitmentDurations, req.Duration) {
5✔
1353
                msg := fmt.Sprintf("provided duration: %s does not match the config %v", req.Duration, behavior.CommitmentDurations)
1✔
1354
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1355
                return
1✔
1356
        }
1✔
1357

1358
        newExpiresAt := req.Duration.AddTo(unwrapOrDefault(dbCommitment.ConfirmBy, dbCommitment.CreatedAt))
3✔
1359
        if newExpiresAt.Before(dbCommitment.ExpiresAt) {
4✔
1360
                msg := fmt.Sprintf("duration change from %s to %s forbidden", dbCommitment.Duration, req.Duration)
1✔
1361
                http.Error(w, msg, http.StatusForbidden)
1✔
1362
                return
1✔
1363
        }
1✔
1364

1365
        dbCommitment.Duration = req.Duration
2✔
1366
        dbCommitment.ExpiresAt = newExpiresAt
2✔
1367
        _, err = p.DB.Update(&dbCommitment)
2✔
1368
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1369
                return
×
1370
        }
×
1371

1372
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
2✔
1373
        p.auditor.Record(audittools.Event{
2✔
1374
                Time:       p.timeNow(),
2✔
1375
                Request:    r,
2✔
1376
                User:       token,
2✔
1377
                ReasonCode: http.StatusOK,
2✔
1378
                Action:     cadf.UpdateAction,
2✔
1379
                Target: commitmentEventTarget{
2✔
1380
                        DomainID:    dbDomain.UUID,
2✔
1381
                        DomainName:  dbDomain.Name,
2✔
1382
                        ProjectID:   dbProject.UUID,
2✔
1383
                        ProjectName: dbProject.Name,
2✔
1384
                        Commitments: []limesresources.Commitment{c},
2✔
1385
                },
2✔
1386
        })
2✔
1387

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