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

sapcc / limes / 13660937622

04 Mar 2025 06:59PM UTC coverage: 79.441% (+0.02%) from 79.426%
13660937622

Pull #674

github

VoigtS
change dbRenewedCommitments to a map instead of two slices
Pull Request #674: Add commitment renewal endpoint

106 of 132 new or added lines in 2 files covered. (80.3%)

75 existing lines in 1 file now uncovered.

6028 of 7588 relevant lines covered (79.44%)

61.57 hits per line

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

79.43
/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 {
83✔
197
        resInfo := p.Cluster.InfoForResource(loc.ServiceType, loc.ResourceName)
83✔
198
        apiIdentity := p.Cluster.BehaviorForResource(loc.ServiceType, loc.ResourceName).IdentityInV1API
83✔
199
        return limesresources.Commitment{
83✔
200
                ID:               int64(c.ID),
83✔
201
                ServiceType:      apiIdentity.ServiceType,
83✔
202
                ResourceName:     apiIdentity.Name,
83✔
203
                AvailabilityZone: loc.AvailabilityZone,
83✔
204
                Amount:           c.Amount,
83✔
205
                Unit:             resInfo.Unit,
83✔
206
                Duration:         c.Duration,
83✔
207
                CreatedAt:        limes.UnixEncodedTime{Time: c.CreatedAt},
83✔
208
                CreatorUUID:      c.CreatorUUID,
83✔
209
                CreatorName:      c.CreatorName,
83✔
210
                CanBeDeleted:     p.canDeleteCommitment(token, c),
83✔
211
                ConfirmBy:        maybeUnixEncodedTime(c.ConfirmBy),
83✔
212
                ConfirmedAt:      maybeUnixEncodedTime(c.ConfirmedAt),
83✔
213
                ExpiresAt:        limes.UnixEncodedTime{Time: c.ExpiresAt},
83✔
214
                TransferStatus:   c.TransferStatus,
83✔
215
                TransferToken:    c.TransferToken,
83✔
216
        }
83✔
217
}
83✔
218

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

44✔
229
        // validate request
44✔
230
        nm := core.BuildResourceNameMapping(p.Cluster)
44✔
231
        dbServiceType, dbResourceName, ok := nm.MapFromV1API(req.ServiceType, req.ResourceName)
44✔
232
        if !ok {
46✔
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)
42✔
238
        resInfo := p.Cluster.InfoForResource(dbServiceType, dbResourceName)
42✔
239
        if len(behavior.CommitmentDurations) == 0 {
43✔
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 {
44✔
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 {
38✔
249
                if !slices.Contains(p.Cluster.Config.AvailabilityZones, req.AvailabilityZone) {
42✔
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) {
37✔
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 {
36✔
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{
34✔
266
                ServiceType:      dbServiceType,
34✔
267
                ResourceName:     dbResourceName,
34✔
268
                AvailabilityZone: req.AvailabilityZone,
34✔
269
        }
34✔
270
        return &req, &loc, &behavior
34✔
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) {
41✔
327
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/new")
41✔
328
        token := p.CheckToken(r)
41✔
329
        if !token.Require(w, "project:edit") {
42✔
330
                return
1✔
331
        }
1✔
332
        dbDomain := p.FindDomainFromRequest(w, r)
40✔
333
        if dbDomain == nil {
41✔
334
                return
1✔
335
        }
1✔
336
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
39✔
337
        if dbProject == nil {
40✔
338
                return
1✔
339
        }
1✔
340
        req, loc, behavior := p.parseAndValidateCommitmentRequest(w, r)
38✔
341
        if req == nil {
49✔
342
                return
11✔
343
        }
11✔
344

345
        var (
27✔
346
                resourceID                db.ProjectResourceID
27✔
347
                azResourceID              db.ProjectAZResourceID
27✔
348
                resourceAllowsCommitments bool
27✔
349
        )
27✔
350
        err := p.DB.QueryRow(findProjectAZResourceIDByLocationQuery, dbProject.ID, loc.ServiceType, loc.ResourceName, loc.AvailabilityZone).
27✔
351
                Scan(&resourceID, &azResourceID, &resourceAllowsCommitments)
27✔
352
        if respondwith.ErrorText(w, err) {
27✔
353
                return
×
354
        }
×
355
        if !resourceAllowsCommitments {
28✔
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()
26✔
363
        if req.ConfirmBy != nil && req.ConfirmBy.Before(now) {
27✔
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) {
30✔
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()
24✔
377
        if respondwith.ErrorText(w, err) {
24✔
378
                return
×
379
        }
×
380
        defer sqlext.RollbackUnlessCommitted(tx)
24✔
381

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

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

24✔
442
        // if the commitment is immediately confirmed, trigger a capacity scrape in
24✔
443
        // order to ApplyComputedProjectQuotas based on the new commitment
24✔
444
        if dbCommitment.ConfirmedAt != nil {
42✔
445
                _, err := p.DB.Exec(forceImmediateCapacityScrapeQuery, now, loc.ServiceType, loc.ResourceName)
18✔
446
                if respondwith.ErrorText(w, err) {
18✔
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)
24✔
453
        if respondwith.ErrorText(w, err) {
24✔
454
                return
×
455
        }
×
456

457
        c := p.convertCommitmentToDisplayForm(dbCommitment, *loc, token)
24✔
458
        respondwith.JSON(w, http.StatusCreated, map[string]any{"commitment": c})
24✔
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✔
480
                return
×
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✔
496
                        return
×
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✔
517
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
518
                return
×
519
        } else if respondwith.ErrorText(w, err) {
1✔
520
                return
×
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✔
526
                return
×
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✔
560
                return
×
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✔
567
                return
×
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✔
577
                return
×
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✔
585
                        return
×
586
                }
×
587
        }
588

589
        err = tx.Commit()
1✔
590
        if respondwith.ErrorText(w, err) {
1✔
591
                return
×
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
// RenewProjectCommitments handles POST /v1/domains/:domain_id/projects/:project_id/commitments/renew.
616
func (p *v1Provider) RenewProjectCommitments(w http.ResponseWriter, r *http.Request) {
6✔
617
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/renew")
6✔
618
        token := p.CheckToken(r)
6✔
619
        if !token.Require(w, "project:edit") {
6✔
NEW
620
                return
×
NEW
621
        }
×
622
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
623
        if dbDomain == nil {
6✔
NEW
624
                return
×
NEW
625
        }
×
626
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
627
        if dbProject == nil {
6✔
NEW
628
                return
×
NEW
629
        }
×
630
        var parseTarget struct {
6✔
631
                CommitmentIDs []db.ProjectCommitmentID `json:"commitment_ids"`
6✔
632
        }
6✔
633
        if !RequireJSON(w, r, &parseTarget) {
6✔
NEW
634
                return
×
NEW
635
        }
×
636

637
        // Load commitments
638
        commitmentIDs := parseTarget.CommitmentIDs
6✔
639
        dbCommitments := make([]db.ProjectCommitment, len(commitmentIDs))
6✔
640
        for i, commitmentID := range commitmentIDs {
14✔
641
                err := p.DB.SelectOne(&dbCommitments[i], findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
8✔
642
                if errors.Is(err, sql.ErrNoRows) {
8✔
NEW
643
                        http.Error(w, "no such commitment", http.StatusNotFound)
×
NEW
644
                        return
×
645
                } else if respondwith.ErrorText(w, err) {
8✔
NEW
646
                        return
×
NEW
647
                }
×
648
        }
649
        now := p.timeNow()
6✔
650

6✔
651
        // Check if commitments are renewable
6✔
652
        for _, dbCommitment := range dbCommitments {
13✔
653
                msg := []string{fmt.Sprintf("CommitmentID: %v", dbCommitment.ID)}
7✔
654
                if dbCommitment.State != db.CommitmentStateActive {
8✔
655
                        msg = append(msg, fmt.Sprintf("invalid commitment state: %s", dbCommitment.State))
1✔
656
                }
1✔
657
                if now.Before(dbCommitment.ExpiresAt.Add(-(3 * 30 * 24 * time.Hour))) {
9✔
658
                        msg = append(msg, "renewal attempt too early")
2✔
659
                }
2✔
660
                if now.After(dbCommitment.ExpiresAt) {
8✔
661
                        msg = append(msg, "commitment expired")
1✔
662
                }
1✔
663
                if dbCommitment.TransferStatus != limesresources.CommitmentTransferStatusNone {
8✔
664
                        msg = append(msg, "commitment in transfer")
1✔
665
                }
1✔
666
                if dbCommitment.WasExtended {
8✔
667
                        msg = append(msg, "commitment already renewed")
1✔
668
                }
1✔
669

670
                if len(msg) > 1 {
12✔
671
                        http.Error(w, strings.Join(msg, " - "), http.StatusConflict)
5✔
672
                        return
5✔
673
                }
5✔
674
        }
675

676
        // Create renewed commitments
677
        tx, err := p.DB.Begin()
1✔
678
        if respondwith.ErrorText(w, err) {
1✔
NEW
679
                return
×
NEW
680
        }
×
681
        defer sqlext.RollbackUnlessCommitted(tx)
1✔
682

1✔
683
        dbRenewedCommitments := make(map[*db.ProjectCommitment]db.CommitmentWorkflowContext)
1✔
684
        for _, commitment := range dbCommitments {
3✔
685
                creationContext := db.CommitmentWorkflowContext{
2✔
686
                        Reason:               db.CommitmentReasonRenew,
2✔
687
                        RelatedCommitmentIDs: []db.ProjectCommitmentID{commitment.ID},
2✔
688
                }
2✔
689
                buf, err := json.Marshal(creationContext)
2✔
690
                if respondwith.ErrorText(w, err) {
2✔
NEW
691
                        return
×
NEW
692
                }
×
693
                dbRenewedCommitment := db.ProjectCommitment{
2✔
694
                        AZResourceID:        commitment.AZResourceID,
2✔
695
                        Amount:              commitment.Amount,
2✔
696
                        Duration:            commitment.Duration,
2✔
697
                        CreatedAt:           now,
2✔
698
                        CreatorUUID:         token.UserUUID(),
2✔
699
                        CreatorName:         fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
2✔
700
                        ConfirmBy:           &commitment.ExpiresAt,
2✔
701
                        ExpiresAt:           commitment.Duration.AddTo(unwrapOrDefault(&commitment.ExpiresAt, now)),
2✔
702
                        State:               db.CommitmentStatePlanned,
2✔
703
                        CreationContextJSON: json.RawMessage(buf),
2✔
704
                }
2✔
705

2✔
706
                err = tx.Insert(&dbRenewedCommitment)
2✔
707
                if respondwith.ErrorText(w, err) {
2✔
NEW
708
                        return
×
NEW
709
                }
×
710
                dbRenewedCommitments[&dbRenewedCommitment] = creationContext
2✔
711

2✔
712
                commitment.WasExtended = true
2✔
713
                _, err = tx.Update(&commitment)
2✔
714
                if respondwith.ErrorText(w, err) {
2✔
NEW
715
                        return
×
NEW
716
                }
×
717
        }
718

719
        err = tx.Commit()
1✔
720
        if respondwith.ErrorText(w, err) {
1✔
NEW
721
                return
×
NEW
722
        }
×
723

724
        // Create resultset and auditlogs
725
        var commitments []limesresources.Commitment
1✔
726
        var auditEvents []commitmentEventTarget
1✔
727
        for commitment, context := range dbRenewedCommitments {
3✔
728
                var loc core.AZResourceLocation
2✔
729
                err := p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, commitment.AZResourceID).
2✔
730
                        Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
2✔
731
                if errors.Is(err, sql.ErrNoRows) {
2✔
NEW
732
                        http.Error(w, "no route to this commitment", http.StatusNotFound)
×
NEW
733
                        return
×
734
                } else if respondwith.ErrorText(w, err) {
2✔
NEW
735
                        return
×
NEW
736
                }
×
737

738
                c := p.convertCommitmentToDisplayForm(*commitment, loc, token)
2✔
739
                commitments = append(commitments, c)
2✔
740
                auditEvents = append(auditEvents, commitmentEventTarget{
2✔
741
                        DomainID:        dbDomain.UUID,
2✔
742
                        DomainName:      dbDomain.Name,
2✔
743
                        ProjectID:       dbProject.UUID,
2✔
744
                        ProjectName:     dbProject.Name,
2✔
745
                        Commitments:     []limesresources.Commitment{c},
2✔
746
                        WorkflowContext: &context,
2✔
747
                })
2✔
748
        }
749

750
        for _, auditEvent := range auditEvents {
3✔
751
                p.auditor.Record(audittools.Event{
2✔
752
                        Time:       p.timeNow(),
2✔
753
                        Request:    r,
2✔
754
                        User:       token,
2✔
755
                        ReasonCode: http.StatusAccepted,
2✔
756
                        Action:     cadf.UpdateAction,
2✔
757
                        Target:     auditEvent,
2✔
758
                })
2✔
759
        }
2✔
760

761
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitments": commitments})
1✔
762
}
763

764
// DeleteProjectCommitment handles DELETE /v1/domains/:domain_id/projects/:project_id/commitments/:id.
765
func (p *v1Provider) DeleteProjectCommitment(w http.ResponseWriter, r *http.Request) {
8✔
766
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id")
8✔
767
        token := p.CheckToken(r)
8✔
768
        if !token.Require(w, "project:edit") { //NOTE: There is a more specific AuthZ check further down below.
8✔
UNCOV
769
                return
×
770
        }
×
771
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
772
        if dbDomain == nil {
9✔
773
                return
1✔
774
        }
1✔
775
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
7✔
776
        if dbProject == nil {
8✔
777
                return
1✔
778
        }
1✔
779

780
        // load commitment
781
        var dbCommitment db.ProjectCommitment
6✔
782
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
6✔
783
        if errors.Is(err, sql.ErrNoRows) {
7✔
784
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
785
                return
1✔
786
        } else if respondwith.ErrorText(w, err) {
6✔
UNCOV
787
                return
×
788
        }
×
789
        var loc core.AZResourceLocation
5✔
790
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
5✔
791
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
5✔
792
        if errors.Is(err, sql.ErrNoRows) {
5✔
UNCOV
793
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
794
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
795
                return
×
796
        } else if respondwith.ErrorText(w, err) {
5✔
UNCOV
797
                return
×
798
        }
×
799

800
        // check authorization for this specific commitment
801
        if !p.canDeleteCommitment(token, dbCommitment) {
6✔
802
                http.Error(w, "Forbidden", http.StatusForbidden)
1✔
803
                return
1✔
804
        }
1✔
805

806
        // perform deletion
807
        _, err = p.DB.Delete(&dbCommitment)
4✔
808
        if respondwith.ErrorText(w, err) {
4✔
UNCOV
809
                return
×
810
        }
×
811
        p.auditor.Record(audittools.Event{
4✔
812
                Time:       p.timeNow(),
4✔
813
                Request:    r,
4✔
814
                User:       token,
4✔
815
                ReasonCode: http.StatusNoContent,
4✔
816
                Action:     cadf.DeleteAction,
4✔
817
                Target: commitmentEventTarget{
4✔
818
                        DomainID:    dbDomain.UUID,
4✔
819
                        DomainName:  dbDomain.Name,
4✔
820
                        ProjectID:   dbProject.UUID,
4✔
821
                        ProjectName: dbProject.Name,
4✔
822
                        Commitments: []limesresources.Commitment{p.convertCommitmentToDisplayForm(dbCommitment, loc, token)},
4✔
823
                },
4✔
824
        })
4✔
825

4✔
826
        w.WriteHeader(http.StatusNoContent)
4✔
827
}
828

829
func (p *v1Provider) canDeleteCommitment(token *gopherpolicy.Token, commitment db.ProjectCommitment) bool {
88✔
830
        // up to 24 hours after creation of fresh commitments, future commitments can still be deleted by their creators
88✔
831
        if commitment.State == db.CommitmentStatePlanned || commitment.State == db.CommitmentStatePending || commitment.State == db.CommitmentStateActive {
176✔
832
                var creationContext db.CommitmentWorkflowContext
88✔
833
                err := json.Unmarshal(commitment.CreationContextJSON, &creationContext)
88✔
834
                if err == nil && creationContext.Reason == db.CommitmentReasonCreate && p.timeNow().Before(commitment.CreatedAt.Add(24*time.Hour)) {
152✔
835
                        if token.Check("project:edit") {
128✔
836
                                return true
64✔
837
                        }
64✔
838
                }
839
        }
840

841
        // afterwards, a more specific permission is required to delete it
842
        //
843
        // This protects cloud admins making capacity planning decisions based on future commitments
844
        // from having their forecasts ruined by project admins suffering from buyer's remorse.
845
        return token.Check("project:uncommit")
24✔
846
}
847

848
// StartCommitmentTransfer handles POST /v1/domains/:id/projects/:id/commitments/:id/start-transfer
849
func (p *v1Provider) StartCommitmentTransfer(w http.ResponseWriter, r *http.Request) {
8✔
850
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id/start-transfer")
8✔
851
        token := p.CheckToken(r)
8✔
852
        if !token.Require(w, "project:edit") {
8✔
UNCOV
853
                return
×
854
        }
×
855
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
856
        if dbDomain == nil {
8✔
UNCOV
857
                return
×
858
        }
×
859
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
8✔
860
        if dbProject == nil {
8✔
UNCOV
861
                return
×
862
        }
×
863
        // TODO: eventually migrate this struct into go-api-declarations
864
        var parseTarget struct {
8✔
865
                Request struct {
8✔
866
                        Amount         uint64                                  `json:"amount"`
8✔
867
                        TransferStatus limesresources.CommitmentTransferStatus `json:"transfer_status,omitempty"`
8✔
868
                } `json:"commitment"`
8✔
869
        }
8✔
870
        if !RequireJSON(w, r, &parseTarget) {
8✔
UNCOV
871
                return
×
872
        }
×
873
        req := parseTarget.Request
8✔
874

8✔
875
        if req.TransferStatus != limesresources.CommitmentTransferStatusUnlisted && req.TransferStatus != limesresources.CommitmentTransferStatusPublic {
8✔
UNCOV
876
                http.Error(w, fmt.Sprintf("Invalid transfer_status code. Must be %s or %s.", limesresources.CommitmentTransferStatusUnlisted, limesresources.CommitmentTransferStatusPublic), http.StatusBadRequest)
×
877
                return
×
878
        }
×
879

880
        if req.Amount <= 0 {
9✔
881
                http.Error(w, "delivered amount needs to be a positive value.", http.StatusBadRequest)
1✔
882
                return
1✔
883
        }
1✔
884

885
        // load commitment
886
        var dbCommitment db.ProjectCommitment
7✔
887
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
7✔
888
        if errors.Is(err, sql.ErrNoRows) {
7✔
UNCOV
889
                http.Error(w, "no such commitment", http.StatusNotFound)
×
890
                return
×
891
        } else if respondwith.ErrorText(w, err) {
7✔
UNCOV
892
                return
×
893
        }
×
894

895
        // Mark whole commitment or a newly created, splitted one as transferrable.
896
        tx, err := p.DB.Begin()
7✔
897
        if respondwith.ErrorText(w, err) {
7✔
UNCOV
898
                return
×
899
        }
×
900
        defer sqlext.RollbackUnlessCommitted(tx)
7✔
901
        transferToken := p.generateTransferToken()
7✔
902

7✔
903
        // Deny requests with a greater amount than the commitment.
7✔
904
        if req.Amount > dbCommitment.Amount {
8✔
905
                http.Error(w, "delivered amount exceeds the commitment amount.", http.StatusBadRequest)
1✔
906
                return
1✔
907
        }
1✔
908

909
        if req.Amount == dbCommitment.Amount {
10✔
910
                dbCommitment.TransferStatus = req.TransferStatus
4✔
911
                dbCommitment.TransferToken = &transferToken
4✔
912
                _, err = tx.Update(&dbCommitment)
4✔
913
                if respondwith.ErrorText(w, err) {
4✔
UNCOV
914
                        return
×
915
                }
×
916
        } else {
2✔
917
                now := p.timeNow()
2✔
918
                transferAmount := req.Amount
2✔
919
                remainingAmount := dbCommitment.Amount - req.Amount
2✔
920
                transferCommitment, err := p.buildSplitCommitment(dbCommitment, transferAmount)
2✔
921
                if respondwith.ErrorText(w, err) {
2✔
UNCOV
922
                        return
×
923
                }
×
924
                transferCommitment.TransferStatus = req.TransferStatus
2✔
925
                transferCommitment.TransferToken = &transferToken
2✔
926
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
2✔
927
                if respondwith.ErrorText(w, err) {
2✔
UNCOV
928
                        return
×
929
                }
×
930
                err = tx.Insert(&transferCommitment)
2✔
931
                if respondwith.ErrorText(w, err) {
2✔
UNCOV
932
                        return
×
933
                }
×
934
                err = tx.Insert(&remainingCommitment)
2✔
935
                if respondwith.ErrorText(w, err) {
2✔
UNCOV
936
                        return
×
937
                }
×
938
                supersedeContext := db.CommitmentWorkflowContext{
2✔
939
                        Reason:               db.CommitmentReasonSplit,
2✔
940
                        RelatedCommitmentIDs: []db.ProjectCommitmentID{transferCommitment.ID, remainingCommitment.ID},
2✔
941
                }
2✔
942
                buf, err := json.Marshal(supersedeContext)
2✔
943
                if respondwith.ErrorText(w, err) {
2✔
UNCOV
944
                        return
×
945
                }
×
946
                dbCommitment.State = db.CommitmentStateSuperseded
2✔
947
                dbCommitment.SupersededAt = &now
2✔
948
                dbCommitment.SupersedeContextJSON = liquids.PointerTo(json.RawMessage(buf))
2✔
949
                _, err = tx.Update(&dbCommitment)
2✔
950
                if respondwith.ErrorText(w, err) {
2✔
UNCOV
951
                        return
×
952
                }
×
953
                dbCommitment = transferCommitment
2✔
954
        }
955
        err = tx.Commit()
6✔
956
        if respondwith.ErrorText(w, err) {
6✔
UNCOV
957
                return
×
958
        }
×
959

960
        var loc core.AZResourceLocation
6✔
961
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
6✔
962
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
6✔
963
        if errors.Is(err, sql.ErrNoRows) {
6✔
UNCOV
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) {
6✔
UNCOV
968
                return
×
969
        }
×
970

971
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
6✔
972
        p.auditor.Record(audittools.Event{
6✔
973
                Time:       p.timeNow(),
6✔
974
                Request:    r,
6✔
975
                User:       token,
6✔
976
                ReasonCode: http.StatusAccepted,
6✔
977
                Action:     cadf.UpdateAction,
6✔
978
                Target: commitmentEventTarget{
6✔
979
                        DomainID:    dbDomain.UUID,
6✔
980
                        DomainName:  dbDomain.Name,
6✔
981
                        ProjectID:   dbProject.UUID,
6✔
982
                        ProjectName: dbProject.Name,
6✔
983
                        Commitments: []limesresources.Commitment{c},
6✔
984
                },
6✔
985
        })
6✔
986
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
6✔
987
}
988

989
func (p *v1Provider) buildSplitCommitment(dbCommitment db.ProjectCommitment, amount uint64) (db.ProjectCommitment, error) {
5✔
990
        now := p.timeNow()
5✔
991
        creationContext := db.CommitmentWorkflowContext{
5✔
992
                Reason:               db.CommitmentReasonSplit,
5✔
993
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
5✔
994
        }
5✔
995
        buf, err := json.Marshal(creationContext)
5✔
996
        if err != nil {
5✔
UNCOV
997
                return db.ProjectCommitment{}, err
×
998
        }
×
999
        return db.ProjectCommitment{
5✔
1000
                AZResourceID:        dbCommitment.AZResourceID,
5✔
1001
                Amount:              amount,
5✔
1002
                Duration:            dbCommitment.Duration,
5✔
1003
                CreatedAt:           now,
5✔
1004
                CreatorUUID:         dbCommitment.CreatorUUID,
5✔
1005
                CreatorName:         dbCommitment.CreatorName,
5✔
1006
                ConfirmBy:           dbCommitment.ConfirmBy,
5✔
1007
                ConfirmedAt:         dbCommitment.ConfirmedAt,
5✔
1008
                ExpiresAt:           dbCommitment.ExpiresAt,
5✔
1009
                CreationContextJSON: json.RawMessage(buf),
5✔
1010
                State:               dbCommitment.State,
5✔
1011
        }, nil
5✔
1012
}
1013

1014
func (p *v1Provider) buildConvertedCommitment(dbCommitment db.ProjectCommitment, azResourceID db.ProjectAZResourceID, amount uint64) (db.ProjectCommitment, error) {
2✔
1015
        now := p.timeNow()
2✔
1016
        creationContext := db.CommitmentWorkflowContext{
2✔
1017
                Reason:               db.CommitmentReasonConvert,
2✔
1018
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1019
        }
2✔
1020
        buf, err := json.Marshal(creationContext)
2✔
1021
        if err != nil {
2✔
UNCOV
1022
                return db.ProjectCommitment{}, err
×
1023
        }
×
1024
        return db.ProjectCommitment{
2✔
1025
                AZResourceID:        azResourceID,
2✔
1026
                Amount:              amount,
2✔
1027
                Duration:            dbCommitment.Duration,
2✔
1028
                CreatedAt:           now,
2✔
1029
                CreatorUUID:         dbCommitment.CreatorUUID,
2✔
1030
                CreatorName:         dbCommitment.CreatorName,
2✔
1031
                ConfirmBy:           dbCommitment.ConfirmBy,
2✔
1032
                ConfirmedAt:         dbCommitment.ConfirmedAt,
2✔
1033
                ExpiresAt:           dbCommitment.ExpiresAt,
2✔
1034
                CreationContextJSON: json.RawMessage(buf),
2✔
1035
                State:               dbCommitment.State,
2✔
1036
        }, nil
2✔
1037
}
1038

1039
// GetCommitmentByTransferToken handles GET /v1/commitments/{token}
1040
func (p *v1Provider) GetCommitmentByTransferToken(w http.ResponseWriter, r *http.Request) {
2✔
1041
        httpapi.IdentifyEndpoint(r, "/v1/commitments/:token")
2✔
1042
        token := p.CheckToken(r)
2✔
1043
        if !token.Require(w, "cluster:show_basic") {
2✔
UNCOV
1044
                return
×
1045
        }
×
1046
        transferToken := mux.Vars(r)["token"]
2✔
1047

2✔
1048
        // The token column is a unique key, so we expect only one result.
2✔
1049
        var dbCommitment db.ProjectCommitment
2✔
1050
        err := p.DB.SelectOne(&dbCommitment, findCommitmentByTransferToken, transferToken)
2✔
1051
        if errors.Is(err, sql.ErrNoRows) {
3✔
1052
                http.Error(w, "no matching commitment found.", http.StatusNotFound)
1✔
1053
                return
1✔
1054
        } else if respondwith.ErrorText(w, err) {
2✔
UNCOV
1055
                return
×
1056
        }
×
1057

1058
        var loc core.AZResourceLocation
1✔
1059
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
1✔
1060
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
1✔
1061
        if errors.Is(err, sql.ErrNoRows) {
1✔
UNCOV
1062
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1063
                http.Error(w, "location data not found.", http.StatusNotFound)
×
1064
                return
×
1065
        } else if respondwith.ErrorText(w, err) {
1✔
UNCOV
1066
                return
×
1067
        }
×
1068

1069
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
1✔
1070
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
1071
}
1072

1073
// TransferCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/transfer-commitment/{id}?token={token}
1074
func (p *v1Provider) TransferCommitment(w http.ResponseWriter, r *http.Request) {
5✔
1075
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/transfer-commitment/:id")
5✔
1076
        token := p.CheckToken(r)
5✔
1077
        if !token.Require(w, "project:edit") {
5✔
UNCOV
1078
                return
×
1079
        }
×
1080
        transferToken := r.Header.Get("Transfer-Token")
5✔
1081
        if transferToken == "" {
6✔
1082
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
1✔
1083
                return
1✔
1084
        }
1✔
1085
        commitmentID := mux.Vars(r)["id"]
4✔
1086
        if commitmentID == "" {
4✔
UNCOV
1087
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1088
                return
×
1089
        }
×
1090
        dbDomain := p.FindDomainFromRequest(w, r)
4✔
1091
        if dbDomain == nil {
4✔
UNCOV
1092
                return
×
1093
        }
×
1094
        targetProject := p.FindProjectFromRequest(w, r, dbDomain)
4✔
1095
        if targetProject == nil {
4✔
UNCOV
1096
                return
×
1097
        }
×
1098

1099
        // find commitment by transfer_token
1100
        var dbCommitment db.ProjectCommitment
4✔
1101
        err := p.DB.SelectOne(&dbCommitment, getCommitmentWithMatchingTransferTokenQuery, commitmentID, transferToken)
4✔
1102
        if errors.Is(err, sql.ErrNoRows) {
5✔
1103
                http.Error(w, "no matching commitment found", http.StatusNotFound)
1✔
1104
                return
1✔
1105
        } else if respondwith.ErrorText(w, err) {
4✔
UNCOV
1106
                return
×
1107
        }
×
1108

1109
        var loc core.AZResourceLocation
3✔
1110
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
3✔
1111
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
3✔
1112
        if errors.Is(err, sql.ErrNoRows) {
3✔
UNCOV
1113
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1114
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1115
                return
×
1116
        } else if respondwith.ErrorText(w, err) {
3✔
UNCOV
1117
                return
×
1118
        }
×
1119

1120
        // get target service and AZ resource
1121
        var (
3✔
1122
                sourceResourceID   db.ProjectResourceID
3✔
1123
                targetResourceID   db.ProjectResourceID
3✔
1124
                targetAZResourceID db.ProjectAZResourceID
3✔
1125
        )
3✔
1126
        err = p.DB.QueryRow(findTargetAZResourceIDBySourceIDQuery, dbCommitment.AZResourceID, targetProject.ID).
3✔
1127
                Scan(&sourceResourceID, &targetResourceID, &targetAZResourceID)
3✔
1128
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
1129
                return
×
1130
        }
×
1131

1132
        // validate that we have enough committable capacity on the receiving side
1133
        tx, err := p.DB.Begin()
3✔
1134
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
1135
                return
×
1136
        }
×
1137
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1138
        ok, err := datamodel.CanMoveExistingCommitment(dbCommitment.Amount, loc, sourceResourceID, targetResourceID, p.Cluster, tx)
3✔
1139
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
1140
                return
×
1141
        }
×
1142
        if !ok {
4✔
1143
                http.Error(w, "not enough committable capacity on the receiving side", http.StatusConflict)
1✔
1144
                return
1✔
1145
        }
1✔
1146

1147
        dbCommitment.TransferStatus = ""
2✔
1148
        dbCommitment.TransferToken = nil
2✔
1149
        dbCommitment.AZResourceID = targetAZResourceID
2✔
1150
        _, err = tx.Update(&dbCommitment)
2✔
1151
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1152
                return
×
1153
        }
×
1154
        err = tx.Commit()
2✔
1155
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1156
                return
×
1157
        }
×
1158

1159
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
2✔
1160
        p.auditor.Record(audittools.Event{
2✔
1161
                Time:       p.timeNow(),
2✔
1162
                Request:    r,
2✔
1163
                User:       token,
2✔
1164
                ReasonCode: http.StatusAccepted,
2✔
1165
                Action:     cadf.UpdateAction,
2✔
1166
                Target: commitmentEventTarget{
2✔
1167
                        DomainID:    dbDomain.UUID,
2✔
1168
                        DomainName:  dbDomain.Name,
2✔
1169
                        ProjectID:   targetProject.UUID,
2✔
1170
                        ProjectName: targetProject.Name,
2✔
1171
                        Commitments: []limesresources.Commitment{c},
2✔
1172
                },
2✔
1173
        })
2✔
1174

2✔
1175
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1176
}
1177

1178
// GetCommitmentConversion handles GET /v1/commitment-conversion/{service_type}/{resource_name}
1179
func (p *v1Provider) GetCommitmentConversions(w http.ResponseWriter, r *http.Request) {
2✔
1180
        httpapi.IdentifyEndpoint(r, "/v1/commitment-conversion/:service_type/:resource_name")
2✔
1181
        token := p.CheckToken(r)
2✔
1182
        if !token.Require(w, "cluster:show_basic") {
2✔
UNCOV
1183
                return
×
1184
        }
×
1185

1186
        // validate request
1187
        vars := mux.Vars(r)
2✔
1188
        nm := core.BuildResourceNameMapping(p.Cluster)
2✔
1189
        sourceServiceType, sourceResourceName, exists := nm.MapFromV1API(
2✔
1190
                limes.ServiceType(vars["service_type"]),
2✔
1191
                limesresources.ResourceName(vars["resource_name"]),
2✔
1192
        )
2✔
1193
        if !exists {
2✔
UNCOV
1194
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", vars["service_type"], vars["resource_name"])
×
1195
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1196
                return
×
1197
        }
×
1198
        sourceBehavior := p.Cluster.BehaviorForResource(sourceServiceType, sourceResourceName)
2✔
1199
        sourceResInfo := p.Cluster.InfoForResource(sourceServiceType, sourceResourceName)
2✔
1200

2✔
1201
        // enumerate possible conversions
2✔
1202
        conversions := make([]limesresources.CommitmentConversionRule, 0)
2✔
1203
        for targetServiceType, quotaPlugin := range p.Cluster.QuotaPlugins {
8✔
1204
                for targetResourceName, targetResInfo := range quotaPlugin.Resources() {
28✔
1205
                        targetBehavior := p.Cluster.BehaviorForResource(targetServiceType, targetResourceName)
22✔
1206
                        if targetBehavior.CommitmentConversion == (core.CommitmentConversion{}) {
30✔
1207
                                continue
8✔
1208
                        }
1209
                        if sourceServiceType == targetServiceType && sourceResourceName == targetResourceName {
16✔
1210
                                continue
2✔
1211
                        }
1212
                        if sourceResInfo.Unit != targetResInfo.Unit {
19✔
1213
                                continue
7✔
1214
                        }
1215
                        if sourceBehavior.CommitmentConversion.Identifier != targetBehavior.CommitmentConversion.Identifier {
6✔
1216
                                continue
1✔
1217
                        }
1218

1219
                        fromAmount, toAmount := p.getCommitmentConversionRate(sourceBehavior, targetBehavior)
4✔
1220
                        apiServiceType, apiResourceName, ok := nm.MapToV1API(targetServiceType, targetResourceName)
4✔
1221
                        if ok {
8✔
1222
                                conversions = append(conversions, limesresources.CommitmentConversionRule{
4✔
1223
                                        FromAmount:     fromAmount,
4✔
1224
                                        ToAmount:       toAmount,
4✔
1225
                                        TargetService:  apiServiceType,
4✔
1226
                                        TargetResource: apiResourceName,
4✔
1227
                                })
4✔
1228
                        }
4✔
1229
                }
1230
        }
1231

1232
        // use a defined sorting to ensure deterministic behavior in tests
1233
        slices.SortFunc(conversions, func(lhs, rhs limesresources.CommitmentConversionRule) int {
8✔
1234
                result := strings.Compare(string(lhs.TargetService), string(rhs.TargetService))
6✔
1235
                if result != 0 {
11✔
1236
                        return result
5✔
1237
                }
5✔
1238
                return strings.Compare(string(lhs.TargetResource), string(rhs.TargetResource))
1✔
1239
        })
1240

1241
        respondwith.JSON(w, http.StatusOK, map[string]any{"conversions": conversions})
2✔
1242
}
1243

1244
// ConvertCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/convert
1245
func (p *v1Provider) ConvertCommitment(w http.ResponseWriter, r *http.Request) {
9✔
1246
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/convert")
9✔
1247
        token := p.CheckToken(r)
9✔
1248
        if !token.Require(w, "project:edit") {
9✔
UNCOV
1249
                return
×
1250
        }
×
1251
        commitmentID := mux.Vars(r)["commitment_id"]
9✔
1252
        if commitmentID == "" {
9✔
UNCOV
1253
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1254
                return
×
1255
        }
×
1256
        dbDomain := p.FindDomainFromRequest(w, r)
9✔
1257
        if dbDomain == nil {
9✔
UNCOV
1258
                return
×
1259
        }
×
1260
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
9✔
1261
        if dbProject == nil {
9✔
UNCOV
1262
                return
×
1263
        }
×
1264

1265
        // section: sourceBehavior
1266
        var dbCommitment db.ProjectCommitment
9✔
1267
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
9✔
1268
        if errors.Is(err, sql.ErrNoRows) {
10✔
1269
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
1270
                return
1✔
1271
        } else if respondwith.ErrorText(w, err) {
9✔
UNCOV
1272
                return
×
1273
        }
×
1274
        var sourceLoc core.AZResourceLocation
8✔
1275
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
8✔
1276
                Scan(&sourceLoc.ServiceType, &sourceLoc.ResourceName, &sourceLoc.AvailabilityZone)
8✔
1277
        if errors.Is(err, sql.ErrNoRows) {
8✔
UNCOV
1278
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1279
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1280
                return
×
1281
        } else if respondwith.ErrorText(w, err) {
8✔
UNCOV
1282
                return
×
1283
        }
×
1284
        sourceBehavior := p.Cluster.BehaviorForResource(sourceLoc.ServiceType, sourceLoc.ResourceName)
8✔
1285

8✔
1286
        // section: targetBehavior
8✔
1287
        var parseTarget struct {
8✔
1288
                Request struct {
8✔
1289
                        TargetService  limes.ServiceType           `json:"target_service"`
8✔
1290
                        TargetResource limesresources.ResourceName `json:"target_resource"`
8✔
1291
                        SourceAmount   uint64                      `json:"source_amount"`
8✔
1292
                        TargetAmount   uint64                      `json:"target_amount"`
8✔
1293
                } `json:"commitment"`
8✔
1294
        }
8✔
1295
        if !RequireJSON(w, r, &parseTarget) {
8✔
UNCOV
1296
                return
×
1297
        }
×
1298
        req := parseTarget.Request
8✔
1299
        nm := core.BuildResourceNameMapping(p.Cluster)
8✔
1300
        targetServiceType, targetResourceName, exists := nm.MapFromV1API(req.TargetService, req.TargetResource)
8✔
1301
        if !exists {
8✔
UNCOV
1302
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", req.TargetService, req.TargetResource)
×
1303
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1304
                return
×
1305
        }
×
1306
        targetBehavior := p.Cluster.BehaviorForResource(targetServiceType, targetResourceName)
8✔
1307
        if sourceLoc.ResourceName == targetResourceName && sourceLoc.ServiceType == targetServiceType {
9✔
1308
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
1✔
1309
                return
1✔
1310
        }
1✔
1311
        if len(targetBehavior.CommitmentDurations) == 0 {
7✔
UNCOV
1312
                msg := fmt.Sprintf("commitments are not enabled for resource %s/%s", req.TargetService, req.TargetResource)
×
1313
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1314
                return
×
1315
        }
×
1316
        if sourceBehavior.CommitmentConversion.Identifier == "" || sourceBehavior.CommitmentConversion.Identifier != targetBehavior.CommitmentConversion.Identifier {
8✔
1317
                msg := fmt.Sprintf("commitment is not convertible into resource %s/%s", req.TargetService, req.TargetResource)
1✔
1318
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1319
                return
1✔
1320
        }
1✔
1321

1322
        // section: conversion
1323
        if req.SourceAmount > dbCommitment.Amount {
6✔
UNCOV
1324
                msg := fmt.Sprintf("unprocessable source amount. provided: %v, commitment: %v", req.SourceAmount, dbCommitment.Amount)
×
1325
                http.Error(w, msg, http.StatusConflict)
×
1326
                return
×
1327
        }
×
1328
        fromAmount, toAmount := p.getCommitmentConversionRate(sourceBehavior, targetBehavior)
6✔
1329
        conversionAmount := (req.SourceAmount / fromAmount) * toAmount
6✔
1330
        remainderAmount := req.SourceAmount % fromAmount
6✔
1331
        if remainderAmount > 0 {
8✔
1332
                msg := fmt.Sprintf("amount: %v does not fit into conversion rate of: %v", req.SourceAmount, fromAmount)
2✔
1333
                http.Error(w, msg, http.StatusConflict)
2✔
1334
                return
2✔
1335
        }
2✔
1336
        if conversionAmount != req.TargetAmount {
5✔
1337
                msg := fmt.Sprintf("conversion mismatch. provided: %v, calculated: %v", req.TargetAmount, conversionAmount)
1✔
1338
                http.Error(w, msg, http.StatusConflict)
1✔
1339
                return
1✔
1340
        }
1✔
1341

1342
        tx, err := p.DB.Begin()
3✔
1343
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
1344
                return
×
1345
        }
×
1346
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1347

3✔
1348
        var (
3✔
1349
                targetResourceID   db.ProjectResourceID
3✔
1350
                targetAZResourceID db.ProjectAZResourceID
3✔
1351
        )
3✔
1352
        err = p.DB.QueryRow(findTargetAZResourceByTargetProjectQuery, dbProject.ID, targetServiceType, targetResourceName, sourceLoc.AvailabilityZone).
3✔
1353
                Scan(&targetResourceID, &targetAZResourceID)
3✔
1354
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
1355
                return
×
1356
        }
×
1357
        // defense in depth. ServiceType and ResourceName of source and target are already checked. Here it's possible to explicitly check the ID's.
1358
        if dbCommitment.AZResourceID == targetAZResourceID {
3✔
UNCOV
1359
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
×
1360
                return
×
1361
        }
×
1362
        targetLoc := core.AZResourceLocation{
3✔
1363
                ServiceType:      targetServiceType,
3✔
1364
                ResourceName:     targetResourceName,
3✔
1365
                AvailabilityZone: sourceLoc.AvailabilityZone,
3✔
1366
        }
3✔
1367
        // The commitment at the source resource was already confirmed and checked.
3✔
1368
        // Therefore only the addition to the target resource has to be checked against.
3✔
1369
        if dbCommitment.ConfirmedAt != nil {
5✔
1370
                ok, err := datamodel.CanConfirmNewCommitment(targetLoc, targetResourceID, conversionAmount, p.Cluster, p.DB)
2✔
1371
                if respondwith.ErrorText(w, err) {
2✔
UNCOV
1372
                        return
×
1373
                }
×
1374
                if !ok {
3✔
1375
                        http.Error(w, "not enough capacity to confirm the commitment", http.StatusUnprocessableEntity)
1✔
1376
                        return
1✔
1377
                }
1✔
1378
        }
1379

1380
        auditEvent := commitmentEventTarget{
2✔
1381
                DomainID:    dbDomain.UUID,
2✔
1382
                DomainName:  dbDomain.Name,
2✔
1383
                ProjectID:   dbProject.UUID,
2✔
1384
                ProjectName: dbProject.Name,
2✔
1385
        }
2✔
1386

2✔
1387
        relatedCommitmentIDs := make([]db.ProjectCommitmentID, 0)
2✔
1388
        remainingAmount := dbCommitment.Amount - req.SourceAmount
2✔
1389
        if remainingAmount > 0 {
3✔
1390
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
1✔
1391
                if respondwith.ErrorText(w, err) {
1✔
UNCOV
1392
                        return
×
1393
                }
×
1394
                relatedCommitmentIDs = append(relatedCommitmentIDs, remainingCommitment.ID)
1✔
1395
                err = tx.Insert(&remainingCommitment)
1✔
1396
                if respondwith.ErrorText(w, err) {
1✔
UNCOV
1397
                        return
×
1398
                }
×
1399
                auditEvent.Commitments = append(auditEvent.Commitments,
1✔
1400
                        p.convertCommitmentToDisplayForm(remainingCommitment, sourceLoc, token),
1✔
1401
                )
1✔
1402
        }
1403

1404
        convertedCommitment, err := p.buildConvertedCommitment(dbCommitment, targetAZResourceID, conversionAmount)
2✔
1405
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1406
                return
×
1407
        }
×
1408
        relatedCommitmentIDs = append(relatedCommitmentIDs, convertedCommitment.ID)
2✔
1409
        err = tx.Insert(&convertedCommitment)
2✔
1410
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1411
                return
×
1412
        }
×
1413

1414
        // supersede the original commitment
1415
        now := p.timeNow()
2✔
1416
        supersedeContext := db.CommitmentWorkflowContext{
2✔
1417
                Reason:               db.CommitmentReasonConvert,
2✔
1418
                RelatedCommitmentIDs: relatedCommitmentIDs,
2✔
1419
        }
2✔
1420
        buf, err := json.Marshal(supersedeContext)
2✔
1421
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1422
                return
×
1423
        }
×
1424
        dbCommitment.State = db.CommitmentStateSuperseded
2✔
1425
        dbCommitment.SupersededAt = &now
2✔
1426
        dbCommitment.SupersedeContextJSON = liquids.PointerTo(json.RawMessage(buf))
2✔
1427
        _, err = tx.Update(&dbCommitment)
2✔
1428
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1429
                return
×
1430
        }
×
1431

1432
        err = tx.Commit()
2✔
1433
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1434
                return
×
1435
        }
×
1436

1437
        c := p.convertCommitmentToDisplayForm(convertedCommitment, targetLoc, token)
2✔
1438
        auditEvent.Commitments = append([]limesresources.Commitment{c}, auditEvent.Commitments...)
2✔
1439
        auditEvent.WorkflowContext = &db.CommitmentWorkflowContext{
2✔
1440
                Reason:               db.CommitmentReasonSplit,
2✔
1441
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1442
        }
2✔
1443
        p.auditor.Record(audittools.Event{
2✔
1444
                Time:       p.timeNow(),
2✔
1445
                Request:    r,
2✔
1446
                User:       token,
2✔
1447
                ReasonCode: http.StatusAccepted,
2✔
1448
                Action:     cadf.UpdateAction,
2✔
1449
                Target:     auditEvent,
2✔
1450
        })
2✔
1451

2✔
1452
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1453
}
1454

1455
func (p *v1Provider) getCommitmentConversionRate(source, target core.ResourceBehavior) (fromAmount, toAmount uint64) {
10✔
1456
        divisor := GetGreatestCommonDivisor(source.CommitmentConversion.Weight, target.CommitmentConversion.Weight)
10✔
1457
        fromAmount = target.CommitmentConversion.Weight / divisor
10✔
1458
        toAmount = source.CommitmentConversion.Weight / divisor
10✔
1459
        return fromAmount, toAmount
10✔
1460
}
10✔
1461

1462
// ExtendCommitmentDuration handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/update-duration
1463
func (p *v1Provider) UpdateCommitmentDuration(w http.ResponseWriter, r *http.Request) {
6✔
1464
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/update-duration")
6✔
1465
        token := p.CheckToken(r)
6✔
1466
        if !token.Require(w, "project:edit") {
6✔
UNCOV
1467
                return
×
1468
        }
×
1469
        commitmentID := mux.Vars(r)["commitment_id"]
6✔
1470
        if commitmentID == "" {
6✔
UNCOV
1471
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1472
                return
×
1473
        }
×
1474
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
1475
        if dbDomain == nil {
6✔
UNCOV
1476
                return
×
1477
        }
×
1478
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
1479
        if dbProject == nil {
6✔
UNCOV
1480
                return
×
1481
        }
×
1482
        var Request struct {
6✔
1483
                Duration limesresources.CommitmentDuration `json:"duration"`
6✔
1484
        }
6✔
1485
        req := Request
6✔
1486
        if !RequireJSON(w, r, &req) {
6✔
UNCOV
1487
                return
×
1488
        }
×
1489

1490
        var dbCommitment db.ProjectCommitment
6✔
1491
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
6✔
1492
        if errors.Is(err, sql.ErrNoRows) {
6✔
UNCOV
1493
                http.Error(w, "no such commitment", http.StatusNotFound)
×
1494
                return
×
1495
        } else if respondwith.ErrorText(w, err) {
6✔
UNCOV
1496
                return
×
1497
        }
×
1498

1499
        now := p.timeNow()
6✔
1500
        if dbCommitment.ExpiresAt.Before(now) || dbCommitment.ExpiresAt.Equal(now) {
7✔
1501
                http.Error(w, "unable to process expired commitment", http.StatusForbidden)
1✔
1502
                return
1✔
1503
        }
1✔
1504

1505
        if dbCommitment.State == db.CommitmentStateSuperseded {
6✔
1506
                msg := fmt.Sprintf("unable to operate on commitment with a state of %s", dbCommitment.State)
1✔
1507
                http.Error(w, msg, http.StatusForbidden)
1✔
1508
                return
1✔
1509
        }
1✔
1510

1511
        var loc core.AZResourceLocation
4✔
1512
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
4✔
1513
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
4✔
1514
        if errors.Is(err, sql.ErrNoRows) {
4✔
UNCOV
1515
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1516
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1517
                return
×
1518
        } else if respondwith.ErrorText(w, err) {
4✔
UNCOV
1519
                return
×
1520
        }
×
1521
        behavior := p.Cluster.BehaviorForResource(loc.ServiceType, loc.ResourceName)
4✔
1522
        if !slices.Contains(behavior.CommitmentDurations, req.Duration) {
5✔
1523
                msg := fmt.Sprintf("provided duration: %s does not match the config %v", req.Duration, behavior.CommitmentDurations)
1✔
1524
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1525
                return
1✔
1526
        }
1✔
1527

1528
        newExpiresAt := req.Duration.AddTo(unwrapOrDefault(dbCommitment.ConfirmBy, dbCommitment.CreatedAt))
3✔
1529
        if newExpiresAt.Before(dbCommitment.ExpiresAt) {
4✔
1530
                msg := fmt.Sprintf("duration change from %s to %s forbidden", dbCommitment.Duration, req.Duration)
1✔
1531
                http.Error(w, msg, http.StatusForbidden)
1✔
1532
                return
1✔
1533
        }
1✔
1534

1535
        dbCommitment.Duration = req.Duration
2✔
1536
        dbCommitment.ExpiresAt = newExpiresAt
2✔
1537
        _, err = p.DB.Update(&dbCommitment)
2✔
1538
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1539
                return
×
1540
        }
×
1541

1542
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
2✔
1543
        p.auditor.Record(audittools.Event{
2✔
1544
                Time:       p.timeNow(),
2✔
1545
                Request:    r,
2✔
1546
                User:       token,
2✔
1547
                ReasonCode: http.StatusOK,
2✔
1548
                Action:     cadf.UpdateAction,
2✔
1549
                Target: commitmentEventTarget{
2✔
1550
                        DomainID:    dbDomain.UUID,
2✔
1551
                        DomainName:  dbDomain.Name,
2✔
1552
                        ProjectID:   dbProject.UUID,
2✔
1553
                        ProjectName: dbProject.Name,
2✔
1554
                        Commitments: []limesresources.Commitment{c},
2✔
1555
                },
2✔
1556
        })
2✔
1557

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