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

sapcc / limes / 13861445880

13 Mar 2025 04:15PM UTC coverage: 79.457% (+0.03%) from 79.426%
13861445880

Pull #674

github

VoigtS
Add was_extended attribute to the commitment API response
Pull Request #674: Add commitment renewal endpoint

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

174 existing lines in 3 files now uncovered.

6034 of 7594 relevant lines covered (79.46%)

61.53 hits per line

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

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

19
package api
20

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
723
                err = tx.Insert(&dbRenewedCommitment)
2✔
724
                if respondwith.ErrorText(w, err) {
2✔
NEW
725
                        return
×
NEW
726
                }
×
727
                dbRenewedCommitments[dbRenewedCommitment.ID] = renewContext{commitment: dbRenewedCommitment, location: loc, context: creationContext}
2✔
728

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

736
        err = tx.Commit()
1✔
737
        if respondwith.ErrorText(w, err) {
1✔
NEW
738
                return
×
NEW
739
        }
×
740

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

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

766
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitments": commitments})
1✔
767
}
768

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

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

805
        // check authorization for this specific commitment
806
        if !p.canDeleteCommitment(token, dbCommitment) {
6✔
807
                http.Error(w, "Forbidden", http.StatusForbidden)
1✔
808
                return
1✔
809
        }
1✔
810

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

4✔
831
        w.WriteHeader(http.StatusNoContent)
4✔
832
}
833

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

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

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

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

885
        if req.Amount <= 0 {
9✔
886
                http.Error(w, "delivered amount needs to be a positive value.", http.StatusBadRequest)
1✔
887
                return
1✔
888
        }
1✔
889

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

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

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

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

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

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

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

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

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

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

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

1074
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token)
1✔
1075
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
1076
}
1077

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

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

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

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

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

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

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

2✔
1180
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1181
}
1182

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

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

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

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

1237
        // use a defined sorting to ensure deterministic behavior in tests
1238
        slices.SortFunc(conversions, func(lhs, rhs limesresources.CommitmentConversionRule) int {
5✔
1239
                result := strings.Compare(string(lhs.TargetService), string(rhs.TargetService))
3✔
1240
                if result != 0 {
5✔
1241
                        return result
2✔
1242
                }
2✔
1243
                return strings.Compare(string(lhs.TargetResource), string(rhs.TargetResource))
1✔
1244
        })
1245

1246
        respondwith.JSON(w, http.StatusOK, map[string]any{"conversions": conversions})
2✔
1247
}
1248

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

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

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

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

1347
        tx, err := p.DB.Begin()
3✔
1348
        if respondwith.ErrorText(w, err) {
3✔
1349
                return
×
1350
        }
×
1351
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1352

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

1385
        auditEvent := commitmentEventTarget{
2✔
1386
                DomainID:    dbDomain.UUID,
2✔
1387
                DomainName:  dbDomain.Name,
2✔
1388
                ProjectID:   dbProject.UUID,
2✔
1389
                ProjectName: dbProject.Name,
2✔
1390
        }
2✔
1391

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

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

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

1437
        err = tx.Commit()
2✔
1438
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1439
                return
×
UNCOV
1440
        }
×
1441

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

2✔
1457
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1458
}
1459

1460
func (p *v1Provider) getCommitmentConversionRate(source, target core.ResourceBehavior) (fromAmount, toAmount uint64) {
10✔
1461
        divisor := GetGreatestCommonDivisor(source.CommitmentConversion.Weight, target.CommitmentConversion.Weight)
10✔
1462
        fromAmount = target.CommitmentConversion.Weight / divisor
10✔
1463
        toAmount = source.CommitmentConversion.Weight / divisor
10✔
1464
        return fromAmount, toAmount
10✔
1465
}
10✔
1466

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

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

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

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

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

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

1540
        dbCommitment.Duration = req.Duration
2✔
1541
        dbCommitment.ExpiresAt = newExpiresAt
2✔
1542
        _, err = p.DB.Update(&dbCommitment)
2✔
1543
        if respondwith.ErrorText(w, err) {
2✔
UNCOV
1544
                return
×
UNCOV
1545
        }
×
1546

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

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