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

sapcc / limes / 14023509211

23 Mar 2025 10:15PM UTC coverage: 79.476% (+0.03%) from 79.445%
14023509211

Pull #674

github

majewsky
review: rename s/WasExtended/WasRenewed/ for consistency
Pull Request #674: Add commitment renewal endpoint

112 of 138 new or added lines in 2 files covered. (81.16%)

173 existing lines in 3 files now uncovered.

6041 of 7601 relevant lines covered (79.48%)

61.55 hits per line

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

79.64
/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
        "maps"
27
        "net/http"
28
        "slices"
29
        "strings"
30
        "time"
31

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

268
        loc := core.AZResourceLocation{
35✔
269
                ServiceType:      dbServiceType,
35✔
270
                ResourceName:     dbResourceName,
35✔
271
                AvailabilityZone: req.AvailabilityZone,
35✔
272
        }
35✔
273
        return &req, &loc, &behavior
35✔
274
}
275

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

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

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

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

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

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

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

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

25✔
385
        // prepare commitment
25✔
386
        confirmBy := maybeUnpackUnixEncodedTime(req.ConfirmBy)
25✔
387
        creationContext := db.CommitmentWorkflowContext{Reason: db.CommitmentReasonCreate}
25✔
388
        buf, err := json.Marshal(creationContext)
25✔
389
        if respondwith.ErrorText(w, err) {
25✔
UNCOV
390
                return
×
391
        }
×
392
        dbCommitment := db.ProjectCommitment{
25✔
393
                AZResourceID:        azResourceID,
25✔
394
                Amount:              req.Amount,
25✔
395
                Duration:            req.Duration,
25✔
396
                CreatedAt:           now,
25✔
397
                CreatorUUID:         token.UserUUID(),
25✔
398
                CreatorName:         fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
25✔
399
                ConfirmBy:           confirmBy,
25✔
400
                ConfirmedAt:         nil, // may be set below
25✔
401
                ExpiresAt:           req.Duration.AddTo(unwrapOrDefault(confirmBy, now)),
25✔
402
                CreationContextJSON: json.RawMessage(buf),
25✔
403
        }
25✔
404
        if req.NotifyOnConfirm && req.ConfirmBy == nil {
26✔
405
                http.Error(w, "notification on confirm cannot be set for commitments with immediate confirmation", http.StatusConflict)
1✔
406
                return
1✔
407
        }
1✔
408
        dbCommitment.NotifyOnConfirm = req.NotifyOnConfirm
24✔
409

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

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

24✔
451
        // if the commitment is immediately confirmed, trigger a capacity scrape in
24✔
452
        // order to ApplyComputedProjectQuotas based on the new commitment
24✔
453
        if dbCommitment.ConfirmedAt != nil {
42✔
454
                _, err := p.DB.Exec(forceImmediateCapacityScrapeQuery, now, loc.ServiceType, loc.ResourceName)
18✔
455
                if respondwith.ErrorText(w, err) {
18✔
UNCOV
456
                        return
×
457
                }
×
458
        }
459

460
        // display the possibly confirmed commitment to the user
461
        err = p.DB.SelectOne(&dbCommitment, `SELECT * FROM project_commitments WHERE id = $1`, dbCommitment.ID)
24✔
462
        if respondwith.ErrorText(w, err) {
24✔
UNCOV
463
                return
×
464
        }
×
465

466
        c := p.convertCommitmentToDisplayForm(dbCommitment, *loc, token)
24✔
467
        respondwith.JSON(w, http.StatusCreated, map[string]any{"commitment": c})
24✔
468
}
469

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

497
        // Load commitments
498
        dbCommitments := make([]db.ProjectCommitment, len(commitmentIDs))
8✔
499
        for i, commitmentID := range commitmentIDs {
24✔
500
                err := p.DB.SelectOne(&dbCommitments[i], findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
16✔
501
                if errors.Is(err, sql.ErrNoRows) {
17✔
502
                        http.Error(w, "no such commitment", http.StatusNotFound)
1✔
503
                        return
1✔
504
                } else if respondwith.ErrorText(w, err) {
16✔
UNCOV
505
                        return
×
506
                }
×
507
        }
508

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

522
        var loc core.AZResourceLocation
1✔
523
        err := p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, azResourceID).
1✔
524
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
1✔
525
        if errors.Is(err, sql.ErrNoRows) {
1✔
UNCOV
526
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
527
                return
×
528
        } else if respondwith.ErrorText(w, err) {
1✔
UNCOV
529
                return
×
530
        }
×
531

532
        // Start transaction for creating new commitment and marking merged commitments as superseded
533
        tx, err := p.DB.Begin()
1✔
534
        if respondwith.ErrorText(w, err) {
1✔
UNCOV
535
                return
×
536
        }
×
537
        defer sqlext.RollbackUnlessCommitted(tx)
1✔
538

1✔
539
        // Create merged template
1✔
540
        now := p.timeNow()
1✔
541
        dbMergedCommitment := db.ProjectCommitment{
1✔
542
                AZResourceID: azResourceID,
1✔
543
                Amount:       0,                                   // overwritten below
1✔
544
                Duration:     limesresources.CommitmentDuration{}, // overwritten below
1✔
545
                CreatedAt:    now,
1✔
546
                CreatorUUID:  token.UserUUID(),
1✔
547
                CreatorName:  fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
1✔
548
                ConfirmedAt:  &now,
1✔
549
                ExpiresAt:    time.Time{}, // overwritten below
1✔
550
                State:        db.CommitmentStateActive,
1✔
551
        }
1✔
552

1✔
553
        // Fill amount and latest expiration date
1✔
554
        for _, dbCommitment := range dbCommitments {
3✔
555
                dbMergedCommitment.Amount += dbCommitment.Amount
2✔
556
                if dbCommitment.ExpiresAt.After(dbMergedCommitment.ExpiresAt) {
4✔
557
                        dbMergedCommitment.ExpiresAt = dbCommitment.ExpiresAt
2✔
558
                        dbMergedCommitment.Duration = dbCommitment.Duration
2✔
559
                }
2✔
560
        }
561

562
        // Fill workflow context
563
        creationContext := db.CommitmentWorkflowContext{
1✔
564
                Reason:               db.CommitmentReasonMerge,
1✔
565
                RelatedCommitmentIDs: commitmentIDs,
1✔
566
        }
1✔
567
        buf, err := json.Marshal(creationContext)
1✔
568
        if respondwith.ErrorText(w, err) {
1✔
UNCOV
569
                return
×
570
        }
×
571
        dbMergedCommitment.CreationContextJSON = json.RawMessage(buf)
1✔
572

1✔
573
        // Insert into database
1✔
574
        err = tx.Insert(&dbMergedCommitment)
1✔
575
        if respondwith.ErrorText(w, err) {
1✔
UNCOV
576
                return
×
577
        }
×
578

579
        // Mark merged commits as superseded
580
        supersedeContext := db.CommitmentWorkflowContext{
1✔
581
                Reason:               db.CommitmentReasonMerge,
1✔
582
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbMergedCommitment.ID},
1✔
583
        }
1✔
584
        buf, err = json.Marshal(supersedeContext)
1✔
585
        if respondwith.ErrorText(w, err) {
1✔
UNCOV
586
                return
×
587
        }
×
588
        for _, dbCommitment := range dbCommitments {
3✔
589
                dbCommitment.SupersededAt = &now
2✔
590
                dbCommitment.SupersedeContextJSON = liquids.PointerTo(json.RawMessage(buf))
2✔
591
                dbCommitment.State = db.CommitmentStateSuperseded
2✔
592
                _, err = tx.Update(&dbCommitment)
2✔
593
                if respondwith.ErrorText(w, err) {
2✔
UNCOV
594
                        return
×
595
                }
×
596
        }
597

598
        err = tx.Commit()
1✔
599
        if respondwith.ErrorText(w, err) {
1✔
UNCOV
600
                return
×
601
        }
×
602

603
        c := p.convertCommitmentToDisplayForm(dbMergedCommitment, loc, token)
1✔
604
        auditEvent := commitmentEventTarget{
1✔
605
                DomainID:        dbDomain.UUID,
1✔
606
                DomainName:      dbDomain.Name,
1✔
607
                ProjectID:       dbProject.UUID,
1✔
608
                ProjectName:     dbProject.Name,
1✔
609
                Commitments:     []limesresources.Commitment{c},
1✔
610
                WorkflowContext: &creationContext,
1✔
611
        }
1✔
612
        p.auditor.Record(audittools.Event{
1✔
613
                Time:       p.timeNow(),
1✔
614
                Request:    r,
1✔
615
                User:       token,
1✔
616
                ReasonCode: http.StatusAccepted,
1✔
617
                Action:     cadf.UpdateAction,
1✔
618
                Target:     auditEvent,
1✔
619
        })
1✔
620

1✔
621
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
622
}
623

624
// RenewProjectCommitments handles POST /v1/domains/:domain_id/projects/:project_id/commitments/renew.
625
func (p *v1Provider) RenewProjectCommitments(w http.ResponseWriter, r *http.Request) {
6✔
626
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/renew")
6✔
627
        token := p.CheckToken(r)
6✔
628
        if !token.Require(w, "project:edit") {
6✔
NEW
629
                return
×
NEW
630
        }
×
631
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
632
        if dbDomain == nil {
6✔
NEW
633
                return
×
NEW
634
        }
×
635
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
636
        if dbProject == nil {
6✔
NEW
637
                return
×
NEW
638
        }
×
639
        var parseTarget struct {
6✔
640
                CommitmentIDs []db.ProjectCommitmentID `json:"commitment_ids"`
6✔
641
        }
6✔
642
        if !RequireJSON(w, r, &parseTarget) {
6✔
NEW
643
                return
×
NEW
644
        }
×
645

646
        // Load commitments
647
        commitmentIDs := parseTarget.CommitmentIDs
6✔
648
        dbCommitments := make([]db.ProjectCommitment, len(commitmentIDs))
6✔
649
        for i, commitmentID := range commitmentIDs {
14✔
650
                err := p.DB.SelectOne(&dbCommitments[i], findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
8✔
651
                if errors.Is(err, sql.ErrNoRows) {
8✔
NEW
652
                        http.Error(w, "no such commitment", http.StatusNotFound)
×
NEW
653
                        return
×
654
                } else if respondwith.ErrorText(w, err) {
8✔
NEW
655
                        return
×
NEW
656
                }
×
657
        }
658
        now := p.timeNow()
6✔
659

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

679
                if len(msg) > 1 {
12✔
680
                        http.Error(w, strings.Join(msg, " - "), http.StatusConflict)
5✔
681
                        return
5✔
682
                }
5✔
683
        }
684

685
        // Create renewed commitments
686
        tx, err := p.DB.Begin()
1✔
687
        if respondwith.ErrorText(w, err) {
1✔
NEW
688
                return
×
NEW
689
        }
×
690
        defer sqlext.RollbackUnlessCommitted(tx)
1✔
691

1✔
692
        type renewContext struct {
1✔
693
                commitment db.ProjectCommitment
1✔
694
                location   core.AZResourceLocation
1✔
695
                context    db.CommitmentWorkflowContext
1✔
696
        }
1✔
697
        dbRenewedCommitments := make(map[db.ProjectCommitmentID]renewContext)
1✔
698
        for _, commitment := range dbCommitments {
3✔
699
                var loc core.AZResourceLocation
2✔
700
                err := p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, commitment.AZResourceID).
2✔
701
                        Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
2✔
702
                if errors.Is(err, sql.ErrNoRows) {
2✔
NEW
703
                        http.Error(w, "no route to this commitment", http.StatusNotFound)
×
NEW
704
                        return
×
705
                } else if respondwith.ErrorText(w, err) {
2✔
NEW
706
                        return
×
NEW
707
                }
×
708

709
                creationContext := db.CommitmentWorkflowContext{
2✔
710
                        Reason:               db.CommitmentReasonRenew,
2✔
711
                        RelatedCommitmentIDs: []db.ProjectCommitmentID{commitment.ID},
2✔
712
                }
2✔
713
                buf, err := json.Marshal(creationContext)
2✔
714
                if respondwith.ErrorText(w, err) {
2✔
NEW
715
                        return
×
NEW
716
                }
×
717
                dbRenewedCommitment := db.ProjectCommitment{
2✔
718
                        AZResourceID:        commitment.AZResourceID,
2✔
719
                        Amount:              commitment.Amount,
2✔
720
                        Duration:            commitment.Duration,
2✔
721
                        CreatedAt:           now,
2✔
722
                        CreatorUUID:         token.UserUUID(),
2✔
723
                        CreatorName:         fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
2✔
724
                        ConfirmBy:           &commitment.ExpiresAt,
2✔
725
                        ExpiresAt:           commitment.Duration.AddTo(unwrapOrDefault(&commitment.ExpiresAt, now)),
2✔
726
                        State:               db.CommitmentStatePlanned,
2✔
727
                        CreationContextJSON: json.RawMessage(buf),
2✔
728
                }
2✔
729

2✔
730
                err = tx.Insert(&dbRenewedCommitment)
2✔
731
                if respondwith.ErrorText(w, err) {
2✔
NEW
732
                        return
×
NEW
733
                }
×
734
                dbRenewedCommitments[dbRenewedCommitment.ID] = renewContext{commitment: dbRenewedCommitment, location: loc, context: creationContext}
2✔
735

2✔
736
                commitment.WasRenewed = true
2✔
737
                _, err = tx.Update(&commitment)
2✔
738
                if respondwith.ErrorText(w, err) {
2✔
NEW
739
                        return
×
NEW
740
                }
×
741
        }
742

743
        err = tx.Commit()
1✔
744
        if respondwith.ErrorText(w, err) {
1✔
NEW
745
                return
×
NEW
746
        }
×
747

748
        // Create resultset and auditlogs
749
        var commitments []limesresources.Commitment
1✔
750
        for _, key := range slices.Sorted(maps.Keys(dbRenewedCommitments)) {
3✔
751
                ctx := dbRenewedCommitments[key]
2✔
752
                c := p.convertCommitmentToDisplayForm(ctx.commitment, ctx.location, token)
2✔
753
                commitments = append(commitments, c)
2✔
754
                auditEvent := commitmentEventTarget{
2✔
755
                        DomainID:        dbDomain.UUID,
2✔
756
                        DomainName:      dbDomain.Name,
2✔
757
                        ProjectID:       dbProject.UUID,
2✔
758
                        ProjectName:     dbProject.Name,
2✔
759
                        Commitments:     []limesresources.Commitment{c},
2✔
760
                        WorkflowContext: &ctx.context,
2✔
761
                }
2✔
762

2✔
763
                p.auditor.Record(audittools.Event{
2✔
764
                        Time:       p.timeNow(),
2✔
765
                        Request:    r,
2✔
766
                        User:       token,
2✔
767
                        ReasonCode: http.StatusAccepted,
2✔
768
                        Action:     cadf.UpdateAction,
2✔
769
                        Target:     auditEvent,
2✔
770
                })
2✔
771
        }
2✔
772

773
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitments": commitments})
1✔
774
}
775

776
// DeleteProjectCommitment handles DELETE /v1/domains/:domain_id/projects/:project_id/commitments/:id.
777
func (p *v1Provider) DeleteProjectCommitment(w http.ResponseWriter, r *http.Request) {
8✔
778
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id")
8✔
779
        token := p.CheckToken(r)
8✔
780
        if !token.Require(w, "project:edit") { //NOTE: There is a more specific AuthZ check further down below.
8✔
UNCOV
781
                return
×
UNCOV
782
        }
×
783
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
784
        if dbDomain == nil {
9✔
785
                return
1✔
786
        }
1✔
787
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
7✔
788
        if dbProject == nil {
8✔
789
                return
1✔
790
        }
1✔
791

792
        // load commitment
793
        var dbCommitment db.ProjectCommitment
6✔
794
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
6✔
795
        if errors.Is(err, sql.ErrNoRows) {
7✔
796
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
797
                return
1✔
798
        } else if respondwith.ErrorText(w, err) {
6✔
UNCOV
799
                return
×
UNCOV
800
        }
×
801
        var loc core.AZResourceLocation
5✔
802
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
5✔
803
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
5✔
804
        if errors.Is(err, sql.ErrNoRows) {
5✔
805
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
806
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
UNCOV
807
                return
×
808
        } else if respondwith.ErrorText(w, err) {
5✔
UNCOV
809
                return
×
UNCOV
810
        }
×
811

812
        // check authorization for this specific commitment
813
        if !p.canDeleteCommitment(token, dbCommitment) {
6✔
814
                http.Error(w, "Forbidden", http.StatusForbidden)
1✔
815
                return
1✔
816
        }
1✔
817

818
        // perform deletion
819
        _, err = p.DB.Delete(&dbCommitment)
4✔
820
        if respondwith.ErrorText(w, err) {
4✔
UNCOV
821
                return
×
UNCOV
822
        }
×
823
        p.auditor.Record(audittools.Event{
4✔
824
                Time:       p.timeNow(),
4✔
825
                Request:    r,
4✔
826
                User:       token,
4✔
827
                ReasonCode: http.StatusNoContent,
4✔
828
                Action:     cadf.DeleteAction,
4✔
829
                Target: commitmentEventTarget{
4✔
830
                        DomainID:    dbDomain.UUID,
4✔
831
                        DomainName:  dbDomain.Name,
4✔
832
                        ProjectID:   dbProject.UUID,
4✔
833
                        ProjectName: dbProject.Name,
4✔
834
                        Commitments: []limesresources.Commitment{p.convertCommitmentToDisplayForm(dbCommitment, loc, token)},
4✔
835
                },
4✔
836
        })
4✔
837

4✔
838
        w.WriteHeader(http.StatusNoContent)
4✔
839
}
840

841
func (p *v1Provider) canDeleteCommitment(token *gopherpolicy.Token, commitment db.ProjectCommitment) bool {
88✔
842
        // up to 24 hours after creation of fresh commitments, future commitments can still be deleted by their creators
88✔
843
        if commitment.State == db.CommitmentStatePlanned || commitment.State == db.CommitmentStatePending || commitment.State == db.CommitmentStateActive {
176✔
844
                var creationContext db.CommitmentWorkflowContext
88✔
845
                err := json.Unmarshal(commitment.CreationContextJSON, &creationContext)
88✔
846
                if err == nil && creationContext.Reason == db.CommitmentReasonCreate && p.timeNow().Before(commitment.CreatedAt.Add(24*time.Hour)) {
152✔
847
                        if token.Check("project:edit") {
128✔
848
                                return true
64✔
849
                        }
64✔
850
                }
851
        }
852

853
        // afterwards, a more specific permission is required to delete it
854
        //
855
        // This protects cloud admins making capacity planning decisions based on future commitments
856
        // from having their forecasts ruined by project admins suffering from buyer's remorse.
857
        return token.Check("project:uncommit")
24✔
858
}
859

860
// StartCommitmentTransfer handles POST /v1/domains/:id/projects/:id/commitments/:id/start-transfer
861
func (p *v1Provider) StartCommitmentTransfer(w http.ResponseWriter, r *http.Request) {
8✔
862
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id/start-transfer")
8✔
863
        token := p.CheckToken(r)
8✔
864
        if !token.Require(w, "project:edit") {
8✔
UNCOV
865
                return
×
UNCOV
866
        }
×
867
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
868
        if dbDomain == nil {
8✔
UNCOV
869
                return
×
UNCOV
870
        }
×
871
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
8✔
872
        if dbProject == nil {
8✔
873
                return
×
874
        }
×
875
        // TODO: eventually migrate this struct into go-api-declarations
876
        var parseTarget struct {
8✔
877
                Request struct {
8✔
878
                        Amount         uint64                                  `json:"amount"`
8✔
879
                        TransferStatus limesresources.CommitmentTransferStatus `json:"transfer_status,omitempty"`
8✔
880
                } `json:"commitment"`
8✔
881
        }
8✔
882
        if !RequireJSON(w, r, &parseTarget) {
8✔
UNCOV
883
                return
×
UNCOV
884
        }
×
885
        req := parseTarget.Request
8✔
886

8✔
887
        if req.TransferStatus != limesresources.CommitmentTransferStatusUnlisted && req.TransferStatus != limesresources.CommitmentTransferStatusPublic {
8✔
888
                http.Error(w, fmt.Sprintf("Invalid transfer_status code. Must be %s or %s.", limesresources.CommitmentTransferStatusUnlisted, limesresources.CommitmentTransferStatusPublic), http.StatusBadRequest)
×
889
                return
×
UNCOV
890
        }
×
891

892
        if req.Amount <= 0 {
9✔
893
                http.Error(w, "delivered amount needs to be a positive value.", http.StatusBadRequest)
1✔
894
                return
1✔
895
        }
1✔
896

897
        // load commitment
898
        var dbCommitment db.ProjectCommitment
7✔
899
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
7✔
900
        if errors.Is(err, sql.ErrNoRows) {
7✔
UNCOV
901
                http.Error(w, "no such commitment", http.StatusNotFound)
×
UNCOV
902
                return
×
903
        } else if respondwith.ErrorText(w, err) {
7✔
UNCOV
904
                return
×
UNCOV
905
        }
×
906

907
        // Mark whole commitment or a newly created, splitted one as transferrable.
908
        tx, err := p.DB.Begin()
7✔
909
        if respondwith.ErrorText(w, err) {
7✔
910
                return
×
911
        }
×
912
        defer sqlext.RollbackUnlessCommitted(tx)
7✔
913
        transferToken := p.generateTransferToken()
7✔
914

7✔
915
        // Deny requests with a greater amount than the commitment.
7✔
916
        if req.Amount > dbCommitment.Amount {
8✔
917
                http.Error(w, "delivered amount exceeds the commitment amount.", http.StatusBadRequest)
1✔
918
                return
1✔
919
        }
1✔
920

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

972
        var loc core.AZResourceLocation
6✔
973
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
6✔
974
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
6✔
975
        if errors.Is(err, sql.ErrNoRows) {
6✔
UNCOV
976
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
UNCOV
977
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
UNCOV
978
                return
×
979
        } else if respondwith.ErrorText(w, err) {
6✔
UNCOV
980
                return
×
UNCOV
981
        }
×
982

983
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
6✔
984
        p.auditor.Record(audittools.Event{
6✔
985
                Time:       p.timeNow(),
6✔
986
                Request:    r,
6✔
987
                User:       token,
6✔
988
                ReasonCode: http.StatusAccepted,
6✔
989
                Action:     cadf.UpdateAction,
6✔
990
                Target: commitmentEventTarget{
6✔
991
                        DomainID:    dbDomain.UUID,
6✔
992
                        DomainName:  dbDomain.Name,
6✔
993
                        ProjectID:   dbProject.UUID,
6✔
994
                        ProjectName: dbProject.Name,
6✔
995
                        Commitments: []limesresources.Commitment{c},
6✔
996
                },
6✔
997
        })
6✔
998
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
6✔
999
}
1000

1001
func (p *v1Provider) buildSplitCommitment(dbCommitment db.ProjectCommitment, amount uint64) (db.ProjectCommitment, error) {
5✔
1002
        now := p.timeNow()
5✔
1003
        creationContext := db.CommitmentWorkflowContext{
5✔
1004
                Reason:               db.CommitmentReasonSplit,
5✔
1005
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
5✔
1006
        }
5✔
1007
        buf, err := json.Marshal(creationContext)
5✔
1008
        if err != nil {
5✔
UNCOV
1009
                return db.ProjectCommitment{}, err
×
UNCOV
1010
        }
×
1011
        return db.ProjectCommitment{
5✔
1012
                AZResourceID:        dbCommitment.AZResourceID,
5✔
1013
                Amount:              amount,
5✔
1014
                Duration:            dbCommitment.Duration,
5✔
1015
                CreatedAt:           now,
5✔
1016
                CreatorUUID:         dbCommitment.CreatorUUID,
5✔
1017
                CreatorName:         dbCommitment.CreatorName,
5✔
1018
                ConfirmBy:           dbCommitment.ConfirmBy,
5✔
1019
                ConfirmedAt:         dbCommitment.ConfirmedAt,
5✔
1020
                ExpiresAt:           dbCommitment.ExpiresAt,
5✔
1021
                CreationContextJSON: json.RawMessage(buf),
5✔
1022
                State:               dbCommitment.State,
5✔
1023
        }, nil
5✔
1024
}
1025

1026
func (p *v1Provider) buildConvertedCommitment(dbCommitment db.ProjectCommitment, azResourceID db.ProjectAZResourceID, amount uint64) (db.ProjectCommitment, error) {
2✔
1027
        now := p.timeNow()
2✔
1028
        creationContext := db.CommitmentWorkflowContext{
2✔
1029
                Reason:               db.CommitmentReasonConvert,
2✔
1030
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1031
        }
2✔
1032
        buf, err := json.Marshal(creationContext)
2✔
1033
        if err != nil {
2✔
UNCOV
1034
                return db.ProjectCommitment{}, err
×
UNCOV
1035
        }
×
1036
        return db.ProjectCommitment{
2✔
1037
                AZResourceID:        azResourceID,
2✔
1038
                Amount:              amount,
2✔
1039
                Duration:            dbCommitment.Duration,
2✔
1040
                CreatedAt:           now,
2✔
1041
                CreatorUUID:         dbCommitment.CreatorUUID,
2✔
1042
                CreatorName:         dbCommitment.CreatorName,
2✔
1043
                ConfirmBy:           dbCommitment.ConfirmBy,
2✔
1044
                ConfirmedAt:         dbCommitment.ConfirmedAt,
2✔
1045
                ExpiresAt:           dbCommitment.ExpiresAt,
2✔
1046
                CreationContextJSON: json.RawMessage(buf),
2✔
1047
                State:               dbCommitment.State,
2✔
1048
        }, nil
2✔
1049
}
1050

1051
// GetCommitmentByTransferToken handles GET /v1/commitments/{token}
1052
func (p *v1Provider) GetCommitmentByTransferToken(w http.ResponseWriter, r *http.Request) {
2✔
1053
        httpapi.IdentifyEndpoint(r, "/v1/commitments/:token")
2✔
1054
        token := p.CheckToken(r)
2✔
1055
        if !token.Require(w, "cluster:show_basic") {
2✔
UNCOV
1056
                return
×
UNCOV
1057
        }
×
1058
        transferToken := mux.Vars(r)["token"]
2✔
1059

2✔
1060
        // The token column is a unique key, so we expect only one result.
2✔
1061
        var dbCommitment db.ProjectCommitment
2✔
1062
        err := p.DB.SelectOne(&dbCommitment, findCommitmentByTransferToken, transferToken)
2✔
1063
        if errors.Is(err, sql.ErrNoRows) {
3✔
1064
                http.Error(w, "no matching commitment found.", http.StatusNotFound)
1✔
1065
                return
1✔
1066
        } else if respondwith.ErrorText(w, err) {
2✔
UNCOV
1067
                return
×
UNCOV
1068
        }
×
1069

1070
        var loc core.AZResourceLocation
1✔
1071
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
1✔
1072
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
1✔
1073
        if errors.Is(err, sql.ErrNoRows) {
1✔
1074
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1075
                http.Error(w, "location data not found.", http.StatusNotFound)
×
UNCOV
1076
                return
×
1077
        } else if respondwith.ErrorText(w, err) {
1✔
UNCOV
1078
                return
×
UNCOV
1079
        }
×
1080

1081
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
1✔
1082
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
1083
}
1084

1085
// TransferCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/transfer-commitment/{id}?token={token}
1086
func (p *v1Provider) TransferCommitment(w http.ResponseWriter, r *http.Request) {
5✔
1087
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/transfer-commitment/:id")
5✔
1088
        token := p.CheckToken(r)
5✔
1089
        if !token.Require(w, "project:edit") {
5✔
UNCOV
1090
                return
×
UNCOV
1091
        }
×
1092
        transferToken := r.Header.Get("Transfer-Token")
5✔
1093
        if transferToken == "" {
6✔
1094
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
1✔
1095
                return
1✔
1096
        }
1✔
1097
        commitmentID := mux.Vars(r)["id"]
4✔
1098
        if commitmentID == "" {
4✔
UNCOV
1099
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
UNCOV
1100
                return
×
UNCOV
1101
        }
×
1102
        dbDomain := p.FindDomainFromRequest(w, r)
4✔
1103
        if dbDomain == nil {
4✔
UNCOV
1104
                return
×
UNCOV
1105
        }
×
1106
        targetProject := p.FindProjectFromRequest(w, r, dbDomain)
4✔
1107
        if targetProject == nil {
4✔
UNCOV
1108
                return
×
1109
        }
×
1110

1111
        // find commitment by transfer_token
1112
        var dbCommitment db.ProjectCommitment
4✔
1113
        err := p.DB.SelectOne(&dbCommitment, getCommitmentWithMatchingTransferTokenQuery, commitmentID, transferToken)
4✔
1114
        if errors.Is(err, sql.ErrNoRows) {
5✔
1115
                http.Error(w, "no matching commitment found", http.StatusNotFound)
1✔
1116
                return
1✔
1117
        } else if respondwith.ErrorText(w, err) {
4✔
UNCOV
1118
                return
×
UNCOV
1119
        }
×
1120

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

1132
        // get target service and AZ resource
1133
        var (
3✔
1134
                sourceResourceID   db.ProjectResourceID
3✔
1135
                targetResourceID   db.ProjectResourceID
3✔
1136
                targetAZResourceID db.ProjectAZResourceID
3✔
1137
        )
3✔
1138
        err = p.DB.QueryRow(findTargetAZResourceIDBySourceIDQuery, dbCommitment.AZResourceID, targetProject.ID).
3✔
1139
                Scan(&sourceResourceID, &targetResourceID, &targetAZResourceID)
3✔
1140
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
1141
                return
×
UNCOV
1142
        }
×
1143

1144
        // validate that we have enough committable capacity on the receiving side
1145
        tx, err := p.DB.Begin()
3✔
1146
        if respondwith.ErrorText(w, err) {
3✔
UNCOV
1147
                return
×
1148
        }
×
1149
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1150
        ok, err := datamodel.CanMoveExistingCommitment(dbCommitment.Amount, loc, sourceResourceID, targetResourceID, p.Cluster, tx)
3✔
1151
        if respondwith.ErrorText(w, err) {
3✔
1152
                return
×
1153
        }
×
1154
        if !ok {
4✔
1155
                http.Error(w, "not enough committable capacity on the receiving side", http.StatusConflict)
1✔
1156
                return
1✔
1157
        }
1✔
1158

1159
        dbCommitment.TransferStatus = ""
2✔
1160
        dbCommitment.TransferToken = nil
2✔
1161
        dbCommitment.AZResourceID = targetAZResourceID
2✔
1162
        _, err = tx.Update(&dbCommitment)
2✔
1163
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1164
                return
×
UNCOV
1165
        }
×
1166
        err = tx.Commit()
2✔
1167
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1168
                return
×
UNCOV
1169
        }
×
1170

1171
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
2✔
1172
        p.auditor.Record(audittools.Event{
2✔
1173
                Time:       p.timeNow(),
2✔
1174
                Request:    r,
2✔
1175
                User:       token,
2✔
1176
                ReasonCode: http.StatusAccepted,
2✔
1177
                Action:     cadf.UpdateAction,
2✔
1178
                Target: commitmentEventTarget{
2✔
1179
                        DomainID:    dbDomain.UUID,
2✔
1180
                        DomainName:  dbDomain.Name,
2✔
1181
                        ProjectID:   targetProject.UUID,
2✔
1182
                        ProjectName: targetProject.Name,
2✔
1183
                        Commitments: []limesresources.Commitment{c},
2✔
1184
                },
2✔
1185
        })
2✔
1186

2✔
1187
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1188
}
1189

1190
// GetCommitmentConversion handles GET /v1/commitment-conversion/{service_type}/{resource_name}
1191
func (p *v1Provider) GetCommitmentConversions(w http.ResponseWriter, r *http.Request) {
2✔
1192
        httpapi.IdentifyEndpoint(r, "/v1/commitment-conversion/:service_type/:resource_name")
2✔
1193
        token := p.CheckToken(r)
2✔
1194
        if !token.Require(w, "cluster:show_basic") {
2✔
UNCOV
1195
                return
×
UNCOV
1196
        }
×
1197

1198
        // validate request
1199
        vars := mux.Vars(r)
2✔
1200
        nm := core.BuildResourceNameMapping(p.Cluster)
2✔
1201
        sourceServiceType, sourceResourceName, exists := nm.MapFromV1API(
2✔
1202
                limes.ServiceType(vars["service_type"]),
2✔
1203
                limesresources.ResourceName(vars["resource_name"]),
2✔
1204
        )
2✔
1205
        if !exists {
2✔
UNCOV
1206
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", vars["service_type"], vars["resource_name"])
×
UNCOV
1207
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
UNCOV
1208
                return
×
UNCOV
1209
        }
×
1210
        sourceBehavior := p.Cluster.BehaviorForResource(sourceServiceType, sourceResourceName)
2✔
1211
        sourceResInfo := p.Cluster.InfoForResource(sourceServiceType, sourceResourceName)
2✔
1212

2✔
1213
        // enumerate possible conversions
2✔
1214
        conversions := make([]limesresources.CommitmentConversionRule, 0)
2✔
1215
        for targetServiceType, quotaPlugin := range p.Cluster.QuotaPlugins {
8✔
1216
                for targetResourceName, targetResInfo := range quotaPlugin.Resources() {
28✔
1217
                        targetBehavior := p.Cluster.BehaviorForResource(targetServiceType, targetResourceName)
22✔
1218
                        if targetBehavior.CommitmentConversion == (core.CommitmentConversion{}) {
30✔
1219
                                continue
8✔
1220
                        }
1221
                        if sourceServiceType == targetServiceType && sourceResourceName == targetResourceName {
16✔
1222
                                continue
2✔
1223
                        }
1224
                        if sourceResInfo.Unit != targetResInfo.Unit {
19✔
1225
                                continue
7✔
1226
                        }
1227
                        if sourceBehavior.CommitmentConversion.Identifier != targetBehavior.CommitmentConversion.Identifier {
6✔
1228
                                continue
1✔
1229
                        }
1230

1231
                        fromAmount, toAmount := p.getCommitmentConversionRate(sourceBehavior, targetBehavior)
4✔
1232
                        apiServiceType, apiResourceName, ok := nm.MapToV1API(targetServiceType, targetResourceName)
4✔
1233
                        if ok {
8✔
1234
                                conversions = append(conversions, limesresources.CommitmentConversionRule{
4✔
1235
                                        FromAmount:     fromAmount,
4✔
1236
                                        ToAmount:       toAmount,
4✔
1237
                                        TargetService:  apiServiceType,
4✔
1238
                                        TargetResource: apiResourceName,
4✔
1239
                                })
4✔
1240
                        }
4✔
1241
                }
1242
        }
1243

1244
        // use a defined sorting to ensure deterministic behavior in tests
1245
        slices.SortFunc(conversions, func(lhs, rhs limesresources.CommitmentConversionRule) int {
5✔
1246
                result := strings.Compare(string(lhs.TargetService), string(rhs.TargetService))
3✔
1247
                if result != 0 {
5✔
1248
                        return result
2✔
1249
                }
2✔
1250
                return strings.Compare(string(lhs.TargetResource), string(rhs.TargetResource))
1✔
1251
        })
1252

1253
        respondwith.JSON(w, http.StatusOK, map[string]any{"conversions": conversions})
2✔
1254
}
1255

1256
// ConvertCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/convert
1257
func (p *v1Provider) ConvertCommitment(w http.ResponseWriter, r *http.Request) {
9✔
1258
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/convert")
9✔
1259
        token := p.CheckToken(r)
9✔
1260
        if !token.Require(w, "project:edit") {
9✔
UNCOV
1261
                return
×
UNCOV
1262
        }
×
1263
        commitmentID := mux.Vars(r)["commitment_id"]
9✔
1264
        if commitmentID == "" {
9✔
UNCOV
1265
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
UNCOV
1266
                return
×
UNCOV
1267
        }
×
1268
        dbDomain := p.FindDomainFromRequest(w, r)
9✔
1269
        if dbDomain == nil {
9✔
UNCOV
1270
                return
×
UNCOV
1271
        }
×
1272
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
9✔
1273
        if dbProject == nil {
9✔
1274
                return
×
1275
        }
×
1276

1277
        // section: sourceBehavior
1278
        var dbCommitment db.ProjectCommitment
9✔
1279
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
9✔
1280
        if errors.Is(err, sql.ErrNoRows) {
10✔
1281
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
1282
                return
1✔
1283
        } else if respondwith.ErrorText(w, err) {
9✔
UNCOV
1284
                return
×
UNCOV
1285
        }
×
1286
        var sourceLoc core.AZResourceLocation
8✔
1287
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
8✔
1288
                Scan(&sourceLoc.ServiceType, &sourceLoc.ResourceName, &sourceLoc.AvailabilityZone)
8✔
1289
        if errors.Is(err, sql.ErrNoRows) {
8✔
UNCOV
1290
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
UNCOV
1291
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1292
                return
×
1293
        } else if respondwith.ErrorText(w, err) {
8✔
UNCOV
1294
                return
×
UNCOV
1295
        }
×
1296
        sourceBehavior := p.Cluster.BehaviorForResource(sourceLoc.ServiceType, sourceLoc.ResourceName)
8✔
1297

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

1334
        // section: conversion
1335
        if req.SourceAmount > dbCommitment.Amount {
6✔
UNCOV
1336
                msg := fmt.Sprintf("unprocessable source amount. provided: %v, commitment: %v", req.SourceAmount, dbCommitment.Amount)
×
UNCOV
1337
                http.Error(w, msg, http.StatusConflict)
×
UNCOV
1338
                return
×
UNCOV
1339
        }
×
1340
        fromAmount, toAmount := p.getCommitmentConversionRate(sourceBehavior, targetBehavior)
6✔
1341
        conversionAmount := (req.SourceAmount / fromAmount) * toAmount
6✔
1342
        remainderAmount := req.SourceAmount % fromAmount
6✔
1343
        if remainderAmount > 0 {
8✔
1344
                msg := fmt.Sprintf("amount: %v does not fit into conversion rate of: %v", req.SourceAmount, fromAmount)
2✔
1345
                http.Error(w, msg, http.StatusConflict)
2✔
1346
                return
2✔
1347
        }
2✔
1348
        if conversionAmount != req.TargetAmount {
5✔
1349
                msg := fmt.Sprintf("conversion mismatch. provided: %v, calculated: %v", req.TargetAmount, conversionAmount)
1✔
1350
                http.Error(w, msg, http.StatusConflict)
1✔
1351
                return
1✔
1352
        }
1✔
1353

1354
        tx, err := p.DB.Begin()
3✔
1355
        if respondwith.ErrorText(w, err) {
3✔
1356
                return
×
1357
        }
×
1358
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1359

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

1392
        auditEvent := commitmentEventTarget{
2✔
1393
                DomainID:    dbDomain.UUID,
2✔
1394
                DomainName:  dbDomain.Name,
2✔
1395
                ProjectID:   dbProject.UUID,
2✔
1396
                ProjectName: dbProject.Name,
2✔
1397
        }
2✔
1398

2✔
1399
        relatedCommitmentIDs := make([]db.ProjectCommitmentID, 0)
2✔
1400
        remainingAmount := dbCommitment.Amount - req.SourceAmount
2✔
1401
        if remainingAmount > 0 {
3✔
1402
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
1✔
1403
                if respondwith.ErrorText(w, err) {
1✔
UNCOV
1404
                        return
×
UNCOV
1405
                }
×
1406
                relatedCommitmentIDs = append(relatedCommitmentIDs, remainingCommitment.ID)
1✔
1407
                err = tx.Insert(&remainingCommitment)
1✔
1408
                if respondwith.ErrorText(w, err) {
1✔
UNCOV
1409
                        return
×
UNCOV
1410
                }
×
1411
                auditEvent.Commitments = append(auditEvent.Commitments,
1✔
1412
                        p.convertCommitmentToDisplayForm(remainingCommitment, sourceLoc, token),
1✔
1413
                )
1✔
1414
        }
1415

1416
        convertedCommitment, err := p.buildConvertedCommitment(dbCommitment, targetAZResourceID, conversionAmount)
2✔
1417
        if respondwith.ErrorText(w, err) {
2✔
1418
                return
×
1419
        }
×
1420
        relatedCommitmentIDs = append(relatedCommitmentIDs, convertedCommitment.ID)
2✔
1421
        err = tx.Insert(&convertedCommitment)
2✔
1422
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1423
                return
×
UNCOV
1424
        }
×
1425

1426
        // supersede the original commitment
1427
        now := p.timeNow()
2✔
1428
        supersedeContext := db.CommitmentWorkflowContext{
2✔
1429
                Reason:               db.CommitmentReasonConvert,
2✔
1430
                RelatedCommitmentIDs: relatedCommitmentIDs,
2✔
1431
        }
2✔
1432
        buf, err := json.Marshal(supersedeContext)
2✔
1433
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1434
                return
×
UNCOV
1435
        }
×
1436
        dbCommitment.State = db.CommitmentStateSuperseded
2✔
1437
        dbCommitment.SupersededAt = &now
2✔
1438
        dbCommitment.SupersedeContextJSON = liquids.PointerTo(json.RawMessage(buf))
2✔
1439
        _, err = tx.Update(&dbCommitment)
2✔
1440
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1441
                return
×
UNCOV
1442
        }
×
1443

1444
        err = tx.Commit()
2✔
1445
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1446
                return
×
UNCOV
1447
        }
×
1448

1449
        c := p.convertCommitmentToDisplayForm(convertedCommitment, targetLoc, token)
2✔
1450
        auditEvent.Commitments = append([]limesresources.Commitment{c}, auditEvent.Commitments...)
2✔
1451
        auditEvent.WorkflowContext = &db.CommitmentWorkflowContext{
2✔
1452
                Reason:               db.CommitmentReasonSplit,
2✔
1453
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1454
        }
2✔
1455
        p.auditor.Record(audittools.Event{
2✔
1456
                Time:       p.timeNow(),
2✔
1457
                Request:    r,
2✔
1458
                User:       token,
2✔
1459
                ReasonCode: http.StatusAccepted,
2✔
1460
                Action:     cadf.UpdateAction,
2✔
1461
                Target:     auditEvent,
2✔
1462
        })
2✔
1463

2✔
1464
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1465
}
1466

1467
func (p *v1Provider) getCommitmentConversionRate(source, target core.ResourceBehavior) (fromAmount, toAmount uint64) {
10✔
1468
        divisor := GetGreatestCommonDivisor(source.CommitmentConversion.Weight, target.CommitmentConversion.Weight)
10✔
1469
        fromAmount = target.CommitmentConversion.Weight / divisor
10✔
1470
        toAmount = source.CommitmentConversion.Weight / divisor
10✔
1471
        return fromAmount, toAmount
10✔
1472
}
10✔
1473

1474
// ExtendCommitmentDuration handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/update-duration
1475
func (p *v1Provider) UpdateCommitmentDuration(w http.ResponseWriter, r *http.Request) {
6✔
1476
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/update-duration")
6✔
1477
        token := p.CheckToken(r)
6✔
1478
        if !token.Require(w, "project:edit") {
6✔
UNCOV
1479
                return
×
UNCOV
1480
        }
×
1481
        commitmentID := mux.Vars(r)["commitment_id"]
6✔
1482
        if commitmentID == "" {
6✔
1483
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1484
                return
×
UNCOV
1485
        }
×
1486
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
1487
        if dbDomain == nil {
6✔
UNCOV
1488
                return
×
1489
        }
×
1490
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
1491
        if dbProject == nil {
6✔
1492
                return
×
1493
        }
×
1494
        var Request struct {
6✔
1495
                Duration limesresources.CommitmentDuration `json:"duration"`
6✔
1496
        }
6✔
1497
        req := Request
6✔
1498
        if !RequireJSON(w, r, &req) {
6✔
UNCOV
1499
                return
×
UNCOV
1500
        }
×
1501

1502
        var dbCommitment db.ProjectCommitment
6✔
1503
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
6✔
1504
        if errors.Is(err, sql.ErrNoRows) {
6✔
UNCOV
1505
                http.Error(w, "no such commitment", http.StatusNotFound)
×
UNCOV
1506
                return
×
1507
        } else if respondwith.ErrorText(w, err) {
6✔
UNCOV
1508
                return
×
UNCOV
1509
        }
×
1510

1511
        now := p.timeNow()
6✔
1512
        if dbCommitment.ExpiresAt.Before(now) || dbCommitment.ExpiresAt.Equal(now) {
7✔
1513
                http.Error(w, "unable to process expired commitment", http.StatusForbidden)
1✔
1514
                return
1✔
1515
        }
1✔
1516

1517
        if dbCommitment.State == db.CommitmentStateSuperseded {
6✔
1518
                msg := fmt.Sprintf("unable to operate on commitment with a state of %s", dbCommitment.State)
1✔
1519
                http.Error(w, msg, http.StatusForbidden)
1✔
1520
                return
1✔
1521
        }
1✔
1522

1523
        var loc core.AZResourceLocation
4✔
1524
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
4✔
1525
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
4✔
1526
        if errors.Is(err, sql.ErrNoRows) {
4✔
UNCOV
1527
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
UNCOV
1528
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
UNCOV
1529
                return
×
1530
        } else if respondwith.ErrorText(w, err) {
4✔
UNCOV
1531
                return
×
UNCOV
1532
        }
×
1533
        behavior := p.Cluster.BehaviorForResource(loc.ServiceType, loc.ResourceName)
4✔
1534
        if !slices.Contains(behavior.CommitmentDurations, req.Duration) {
5✔
1535
                msg := fmt.Sprintf("provided duration: %s does not match the config %v", req.Duration, behavior.CommitmentDurations)
1✔
1536
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1537
                return
1✔
1538
        }
1✔
1539

1540
        newExpiresAt := req.Duration.AddTo(unwrapOrDefault(dbCommitment.ConfirmBy, dbCommitment.CreatedAt))
3✔
1541
        if newExpiresAt.Before(dbCommitment.ExpiresAt) {
4✔
1542
                msg := fmt.Sprintf("duration change from %s to %s forbidden", dbCommitment.Duration, req.Duration)
1✔
1543
                http.Error(w, msg, http.StatusForbidden)
1✔
1544
                return
1✔
1545
        }
1✔
1546

1547
        dbCommitment.Duration = req.Duration
2✔
1548
        dbCommitment.ExpiresAt = newExpiresAt
2✔
1549
        _, err = p.DB.Update(&dbCommitment)
2✔
1550
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1551
                return
×
UNCOV
1552
        }
×
1553

1554
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
2✔
1555
        p.auditor.Record(audittools.Event{
2✔
1556
                Time:       p.timeNow(),
2✔
1557
                Request:    r,
2✔
1558
                User:       token,
2✔
1559
                ReasonCode: http.StatusOK,
2✔
1560
                Action:     cadf.UpdateAction,
2✔
1561
                Target: commitmentEventTarget{
2✔
1562
                        DomainID:    dbDomain.UUID,
2✔
1563
                        DomainName:  dbDomain.Name,
2✔
1564
                        ProjectID:   dbProject.UUID,
2✔
1565
                        ProjectName: dbProject.Name,
2✔
1566
                        Commitments: []limesresources.Commitment{c},
2✔
1567
                },
2✔
1568
        })
2✔
1569

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