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

sapcc / limes / 14038009506

24 Mar 2025 02:34PM UTC coverage: 79.43% (-0.02%) from 79.445%
14038009506

Pull #674

github

majewsky
replace project_commitments.{was_renewed => renew_context_json}

For consistency with the other workflow context columns.
Pull Request #674: Add commitment renewal endpoint

95 of 121 new or added lines in 2 files covered. (78.51%)

8 existing lines in 1 file now uncovered.

6024 of 7584 relevant lines covered (79.43%)

61.67 hits per line

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

79.36
/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/majewsky/gg/option"
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/errext"
39
        "github.com/sapcc/go-bits/gopherpolicy"
40
        "github.com/sapcc/go-bits/httpapi"
41
        "github.com/sapcc/go-bits/must"
42
        "github.com/sapcc/go-bits/respondwith"
43
        "github.com/sapcc/go-bits/sqlext"
44

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

628
// RenewProjectCommitments handles POST /v1/domains/:domain_id/projects/:project_id/commitments/:id/renew.
629
func (p *v1Provider) RenewProjectCommitments(w http.ResponseWriter, r *http.Request) {
6✔
630
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id/renew")
6✔
631
        token := p.CheckToken(r)
6✔
632
        if !token.Require(w, "project:edit") {
6✔
NEW
633
                return
×
NEW
634
        }
×
635
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
636
        if dbDomain == nil {
6✔
NEW
637
                return
×
NEW
638
        }
×
639
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
640
        if dbProject == nil {
6✔
NEW
641
                return
×
NEW
642
        }
×
643

644
        // Load commitment
645
        var dbCommitment db.ProjectCommitment
6✔
646
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
6✔
647
        if errors.Is(err, sql.ErrNoRows) {
6✔
NEW
648
                http.Error(w, "no such commitment", http.StatusNotFound)
×
NEW
649
                return
×
650
        } else if respondwith.ErrorText(w, err) {
6✔
NEW
651
                return
×
NEW
652
        }
×
653
        now := p.timeNow()
6✔
654

6✔
655
        // Check if commitment can be renewed
6✔
656
        var errs errext.ErrorSet
6✔
657
        if dbCommitment.State != db.CommitmentStateActive {
7✔
658
                errs.Addf("invalid state %q", dbCommitment.State)
1✔
659
        } else if now.After(dbCommitment.ExpiresAt) {
7✔
660
                errs.Addf("invalid state %q", db.CommitmentStateExpired)
1✔
661
        }
1✔
662
        if now.Before(dbCommitment.ExpiresAt.Add(-commitmentRenewalPeriod)) {
7✔
663
                errs.Addf("renewal attempt too early")
1✔
664
        }
1✔
665
        if dbCommitment.RenewContextJSON.IsSome() {
7✔
666
                errs.Addf("already renewed")
1✔
667
        }
1✔
668

669
        if !errs.IsEmpty() {
10✔
670
                msg := "cannot renew this commitment: " + errs.Join(", ")
4✔
671
                http.Error(w, msg, http.StatusConflict)
4✔
672
                return
4✔
673
        }
4✔
674

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

2✔
682
        var loc core.AZResourceLocation
2✔
683
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
2✔
684
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
2✔
685
        if errors.Is(err, sql.ErrNoRows) {
2✔
NEW
686
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
NEW
687
                return
×
688
        } else if respondwith.ErrorText(w, err) {
2✔
NEW
689
                return
×
NEW
690
        }
×
691

692
        creationContext := db.CommitmentWorkflowContext{
2✔
693
                Reason:               db.CommitmentReasonRenew,
2✔
694
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbCommitment.ID},
2✔
695
        }
2✔
696
        buf, err := json.Marshal(creationContext)
2✔
697
        if respondwith.ErrorText(w, err) {
2✔
NEW
698
                return
×
NEW
699
        }
×
700
        dbRenewedCommitment := db.ProjectCommitment{
2✔
701
                AZResourceID:        dbCommitment.AZResourceID,
2✔
702
                Amount:              dbCommitment.Amount,
2✔
703
                Duration:            dbCommitment.Duration,
2✔
704
                CreatedAt:           now,
2✔
705
                CreatorUUID:         token.UserUUID(),
2✔
706
                CreatorName:         fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
2✔
707
                ConfirmBy:           &dbCommitment.ExpiresAt,
2✔
708
                ExpiresAt:           dbCommitment.Duration.AddTo(dbCommitment.ExpiresAt),
2✔
709
                State:               db.CommitmentStatePlanned,
2✔
710
                CreationContextJSON: json.RawMessage(buf),
2✔
711
        }
2✔
712

2✔
713
        err = tx.Insert(&dbRenewedCommitment)
2✔
714
        if respondwith.ErrorText(w, err) {
2✔
NEW
715
                return
×
NEW
716
        }
×
717

718
        renewContext := db.CommitmentWorkflowContext{
2✔
719
                Reason:               db.CommitmentReasonRenew,
2✔
720
                RelatedCommitmentIDs: []db.ProjectCommitmentID{dbRenewedCommitment.ID},
2✔
721
        }
2✔
722
        buf, err = json.Marshal(renewContext)
2✔
723
        if respondwith.ErrorText(w, err) {
2✔
NEW
724
                return
×
NEW
725
        }
×
726
        dbCommitment.RenewContextJSON = Some(json.RawMessage(buf))
2✔
727
        _, err = tx.Update(&dbCommitment)
2✔
728
        if respondwith.ErrorText(w, err) {
2✔
NEW
729
                return
×
NEW
730
        }
×
731

732
        err = tx.Commit()
2✔
733
        if respondwith.ErrorText(w, err) {
2✔
NEW
734
                return
×
NEW
735
        }
×
736

737
        // Create resultset and auditlogs
738
        c := p.convertCommitmentToDisplayForm(dbRenewedCommitment, loc, token)
2✔
739
        auditEvent := commitmentEventTarget{
2✔
740
                DomainID:        dbDomain.UUID,
2✔
741
                DomainName:      dbDomain.Name,
2✔
742
                ProjectID:       dbProject.UUID,
2✔
743
                ProjectName:     dbProject.Name,
2✔
744
                Commitments:     []limesresources.Commitment{c},
2✔
745
                WorkflowContext: &creationContext,
2✔
746
        }
2✔
747

2✔
748
        p.auditor.Record(audittools.Event{
2✔
749
                Time:       p.timeNow(),
2✔
750
                Request:    r,
2✔
751
                User:       token,
2✔
752
                ReasonCode: http.StatusAccepted,
2✔
753
                Action:     cadf.UpdateAction,
2✔
754
                Target:     auditEvent,
2✔
755
        })
2✔
756

2✔
757
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
758
}
759

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

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

796
        // check authorization for this specific commitment
797
        if !p.canDeleteCommitment(token, dbCommitment) {
6✔
798
                http.Error(w, "Forbidden", http.StatusForbidden)
1✔
799
                return
1✔
800
        }
1✔
801

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

4✔
822
        w.WriteHeader(http.StatusNoContent)
4✔
823
}
824

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

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

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

8✔
871
        if req.TransferStatus != limesresources.CommitmentTransferStatusUnlisted && req.TransferStatus != limesresources.CommitmentTransferStatusPublic {
8✔
872
                http.Error(w, fmt.Sprintf("Invalid transfer_status code. Must be %s or %s.", limesresources.CommitmentTransferStatusUnlisted, limesresources.CommitmentTransferStatusPublic), http.StatusBadRequest)
×
873
                return
×
874
        }
×
875

876
        if req.Amount <= 0 {
9✔
877
                http.Error(w, "delivered amount needs to be a positive value.", http.StatusBadRequest)
1✔
878
                return
1✔
879
        }
1✔
880

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

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

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

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

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

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

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

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

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

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

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

1065
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
1✔
1066
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
1067
}
1068

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

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

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

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

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

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

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

2✔
1171
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1172
}
1173

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

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

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

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

1228
        // use a defined sorting to ensure deterministic behavior in tests
1229
        slices.SortFunc(conversions, func(lhs, rhs limesresources.CommitmentConversionRule) int {
6✔
1230
                result := strings.Compare(string(lhs.TargetService), string(rhs.TargetService))
4✔
1231
                if result != 0 {
7✔
1232
                        return result
3✔
1233
                }
3✔
1234
                return strings.Compare(string(lhs.TargetResource), string(rhs.TargetResource))
1✔
1235
        })
1236

1237
        respondwith.JSON(w, http.StatusOK, map[string]any{"conversions": conversions})
2✔
1238
}
1239

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

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

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

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

1338
        tx, err := p.DB.Begin()
3✔
1339
        if respondwith.ErrorText(w, err) {
3✔
1340
                return
×
1341
        }
×
1342
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1343

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

1376
        auditEvent := commitmentEventTarget{
2✔
1377
                DomainID:    dbDomain.UUID,
2✔
1378
                DomainName:  dbDomain.Name,
2✔
1379
                ProjectID:   dbProject.UUID,
2✔
1380
                ProjectName: dbProject.Name,
2✔
1381
        }
2✔
1382

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

1400
        convertedCommitment, err := p.buildConvertedCommitment(dbCommitment, targetAZResourceID, conversionAmount)
2✔
1401
        if respondwith.ErrorText(w, err) {
2✔
1402
                return
×
1403
        }
×
1404
        relatedCommitmentIDs = append(relatedCommitmentIDs, convertedCommitment.ID)
2✔
1405
        err = tx.Insert(&convertedCommitment)
2✔
1406
        if respondwith.ErrorText(w, err) {
2✔
1407
                return
×
1408
        }
×
1409

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

1428
        err = tx.Commit()
2✔
1429
        if respondwith.ErrorText(w, err) {
2✔
1430
                return
×
1431
        }
×
1432

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

2✔
1448
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1449
}
1450

1451
func (p *v1Provider) getCommitmentConversionRate(source, target core.ResourceBehavior) (fromAmount, toAmount uint64) {
10✔
1452
        divisor := GetGreatestCommonDivisor(source.CommitmentConversion.Weight, target.CommitmentConversion.Weight)
10✔
1453
        fromAmount = target.CommitmentConversion.Weight / divisor
10✔
1454
        toAmount = source.CommitmentConversion.Weight / divisor
10✔
1455
        return fromAmount, toAmount
10✔
1456
}
10✔
1457

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

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

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

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

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

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

1531
        dbCommitment.Duration = req.Duration
2✔
1532
        dbCommitment.ExpiresAt = newExpiresAt
2✔
1533
        _, err = p.DB.Update(&dbCommitment)
2✔
1534
        if respondwith.ErrorText(w, err) {
2✔
1535
                return
×
1536
        }
×
1537

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

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