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

sapcc / limes / 13661076992

04 Mar 2025 07:08PM UTC coverage: 79.449% (+0.02%) from 79.426%
13661076992

Pull #674

github

VoigtS
load commitment location before critical result generation
Pull Request #674: Add commitment renewal endpoint

109 of 135 new or added lines in 2 files covered. (80.74%)

195 existing lines in 3 files now uncovered.

6031 of 7591 relevant lines covered (79.45%)

61.54 hits per line

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

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

19
package api
20

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
683
        type locationContext struct {
1✔
684
                location core.AZResourceLocation
1✔
685
                context  db.CommitmentWorkflowContext
1✔
686
        }
1✔
687
        dbRenewedCommitments := make(map[*db.ProjectCommitment]locationContext)
1✔
688
        for _, commitment := range dbCommitments {
3✔
689
                var loc core.AZResourceLocation
2✔
690
                err := p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, commitment.AZResourceID).
2✔
691
                        Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
2✔
692
                if errors.Is(err, sql.ErrNoRows) {
2✔
NEW
693
                        http.Error(w, "no route to this commitment", http.StatusNotFound)
×
NEW
694
                        return
×
695
                } else if respondwith.ErrorText(w, err) {
2✔
NEW
696
                        return
×
NEW
697
                }
×
698

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

2✔
720
                err = tx.Insert(&dbRenewedCommitment)
2✔
721
                if respondwith.ErrorText(w, err) {
2✔
NEW
722
                        return
×
NEW
723
                }
×
724
                dbRenewedCommitments[&dbRenewedCommitment] = locationContext{location: loc, context: creationContext}
2✔
725

2✔
726
                commitment.WasExtended = true
2✔
727
                _, err = tx.Update(&commitment)
2✔
728
                if respondwith.ErrorText(w, err) {
2✔
NEW
729
                        return
×
NEW
730
                }
×
731
        }
732

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

738
        // Create resultset and auditlogs
739
        var commitments []limesresources.Commitment
1✔
740
        for commitment, lc := range dbRenewedCommitments {
3✔
741
                c := p.convertCommitmentToDisplayForm(*commitment, lc.location, token)
2✔
742
                commitments = append(commitments, c)
2✔
743
                auditEvent := commitmentEventTarget{
2✔
744
                        DomainID:        dbDomain.UUID,
2✔
745
                        DomainName:      dbDomain.Name,
2✔
746
                        ProjectID:       dbProject.UUID,
2✔
747
                        ProjectName:     dbProject.Name,
2✔
748
                        Commitments:     []limesresources.Commitment{c},
2✔
749
                        WorkflowContext: &lc.context,
2✔
750
                }
2✔
751

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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