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

sapcc / limes / 15901813272

26 Jun 2025 12:27PM UTC coverage: 78.476% (-0.7%) from 79.155%
15901813272

push

github

web-flow
Merge pull request #725 from sapcc/utilize_service_info_from_db2

utilize ServiceInfo from database for collect-startup and serve-tasks

680 of 862 new or added lines in 31 files covered. (78.89%)

12 existing lines in 4 files now uncovered.

6694 of 8530 relevant lines covered (78.48%)

55.41 hits per line

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

77.58
/internal/api/commitment.go
1
// SPDX-FileCopyrightText: 2023 SAP SE or an SAP affiliate company
2
// SPDX-License-Identifier: Apache-2.0
3

4
package api
5

6
import (
7
        "cmp"
8
        "database/sql"
9
        "encoding/json"
10
        "errors"
11
        "fmt"
12
        "maps"
13
        "net/http"
14
        "slices"
15
        "strings"
16
        "time"
17

18
        "github.com/gorilla/mux"
19
        . "github.com/majewsky/gg/option"
20
        "github.com/majewsky/gg/options"
21
        "github.com/sapcc/go-api-declarations/cadf"
22
        "github.com/sapcc/go-api-declarations/limes"
23
        limesresources "github.com/sapcc/go-api-declarations/limes/resources"
24
        "github.com/sapcc/go-api-declarations/liquid"
25
        "github.com/sapcc/go-bits/audittools"
26
        "github.com/sapcc/go-bits/errext"
27
        "github.com/sapcc/go-bits/gopherpolicy"
28
        "github.com/sapcc/go-bits/httpapi"
29
        "github.com/sapcc/go-bits/must"
30
        "github.com/sapcc/go-bits/respondwith"
31
        "github.com/sapcc/go-bits/sqlext"
32

33
        "github.com/sapcc/limes/internal/core"
34
        "github.com/sapcc/limes/internal/datamodel"
35
        "github.com/sapcc/limes/internal/db"
36
        "github.com/sapcc/limes/internal/reports"
37
)
38

39
var (
40
        getProjectCommitmentsQuery = sqlext.SimplifyWhitespace(`
41
                SELECT pc.*
42
                  FROM project_commitments pc
43
                  JOIN project_az_resources par ON pc.az_resource_id = par.id
44
                  JOIN project_resources pr ON par.resource_id = pr.id {{AND pr.name = $resource_name}}
45
                  JOIN project_services ps ON pr.service_id = ps.id {{AND ps.type = $service_type}}
46
                 WHERE %s AND pc.state NOT IN ('superseded', 'expired')
47
                 ORDER BY pc.id
48
        `)
49

50
        getProjectAZResourceLocationsQuery = sqlext.SimplifyWhitespace(`
51
                SELECT par.id, ps.type, pr.name, par.az
52
                  FROM project_az_resources par
53
                  JOIN project_resources pr ON par.resource_id = pr.id {{AND pr.name = $resource_name}}
54
                  JOIN project_services ps ON pr.service_id = ps.id {{AND ps.type = $service_type}}
55
                 WHERE %s
56
        `)
57

58
        findProjectCommitmentByIDQuery = sqlext.SimplifyWhitespace(`
59
                SELECT pc.*
60
                  FROM project_commitments pc
61
                  JOIN project_az_resources par ON pc.az_resource_id = par.id
62
                  JOIN project_resources pr ON par.resource_id = pr.id
63
                  JOIN project_services ps ON pr.service_id = ps.id
64
                 WHERE pc.id = $1 AND ps.project_id = $2
65
        `)
66

67
        // NOTE: The third output column is `resourceAllowsCommitments`.
68
        findProjectAZResourceIDByLocationQuery = sqlext.SimplifyWhitespace(`
69
                SELECT pr.id, par.id, pr.forbidden IS NOT TRUE
70
                  FROM project_az_resources par
71
                  JOIN project_resources pr ON par.resource_id = pr.id
72
                  JOIN project_services ps ON pr.service_id = ps.id
73
                 WHERE ps.project_id = $1 AND ps.type = $2 AND pr.name = $3 AND par.az = $4
74
        `)
75

76
        findProjectAZResourceLocationByIDQuery = sqlext.SimplifyWhitespace(`
77
                SELECT ps.type, pr.name, par.az
78
                  FROM project_az_resources par
79
                  JOIN project_resources pr ON par.resource_id = pr.id
80
                  JOIN project_services ps ON pr.service_id = ps.id
81
                 WHERE par.id = $1
82
        `)
83
        getCommitmentWithMatchingTransferTokenQuery = sqlext.SimplifyWhitespace(`
84
                SELECT * FROM project_commitments WHERE id = $1 AND transfer_token = $2
85
        `)
86
        findCommitmentByTransferToken = sqlext.SimplifyWhitespace(`
87
                SELECT * FROM project_commitments WHERE transfer_token = $1
88
        `)
89
        findTargetAZResourceIDBySourceIDQuery = sqlext.SimplifyWhitespace(`
90
                WITH source as (
91
                SELECT pr.id AS resource_id, ps.type, pr.name, par.az
92
                  FROM project_az_resources as 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
                SELECT s.resource_id, pr.id, par.id
98
                  FROM project_az_resources as par
99
                  JOIN project_resources pr ON par.resource_id = pr.id
100
                  JOIN project_services ps ON pr.service_id = ps.id
101
                  JOIN source s ON ps.type = s.type AND pr.name = s.name AND par.az = s.az
102
                 WHERE ps.project_id = $2
103
        `)
104
        findTargetAZResourceByTargetProjectQuery = sqlext.SimplifyWhitespace(`
105
                SELECT pr.id, par.id
106
                  FROM project_az_resources 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 ps.project_id = $1 AND ps.type = $2 AND pr.name = $3 AND par.az = $4
110
        `)
111
)
112

113
// GetProjectCommitments handles GET /v1/domains/:domain_id/projects/:project_id/commitments.
114
func (p *v1Provider) GetProjectCommitments(w http.ResponseWriter, r *http.Request) {
15✔
115
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments")
15✔
116
        token := p.CheckToken(r)
15✔
117
        if !token.Require(w, "project:show") {
16✔
118
                return
1✔
119
        }
1✔
120
        dbDomain := p.FindDomainFromRequest(w, r)
14✔
121
        if dbDomain == nil {
15✔
122
                return
1✔
123
        }
1✔
124
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
13✔
125
        if dbProject == nil {
14✔
126
                return
1✔
127
        }
1✔
128
        serviceInfos, err := p.Cluster.AllServiceInfos()
12✔
129
        if respondwith.ErrorText(w, err) {
12✔
NEW
130
                return
×
NEW
131
        }
×
132

133
        // enumerate project AZ resources
134
        filter := reports.ReadFilter(r, p.Cluster, serviceInfos)
12✔
135
        queryStr, joinArgs := filter.PrepareQuery(getProjectAZResourceLocationsQuery)
12✔
136
        whereStr, whereArgs := db.BuildSimpleWhereClause(map[string]any{"ps.project_id": dbProject.ID}, len(joinArgs))
12✔
137
        azResourceLocationsByID := make(map[db.ProjectAZResourceID]core.AZResourceLocation)
12✔
138
        err = sqlext.ForeachRow(p.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {
137✔
139
                var (
125✔
140
                        id  db.ProjectAZResourceID
125✔
141
                        loc core.AZResourceLocation
125✔
142
                )
125✔
143
                err := rows.Scan(&id, &loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
125✔
144
                if err != nil {
125✔
145
                        return err
×
146
                }
×
147
                // this check is defense in depth (the DB should be consistent with our config)
148
                if core.HasResource(serviceInfos, loc.ServiceType, loc.ResourceName) {
223✔
149
                        azResourceLocationsByID[id] = loc
98✔
150
                }
98✔
151
                return nil
125✔
152
        })
153
        if respondwith.ErrorText(w, err) {
12✔
154
                return
×
155
        }
×
156

157
        // enumerate relevant project commitments
158
        queryStr, joinArgs = filter.PrepareQuery(getProjectCommitmentsQuery)
12✔
159
        whereStr, whereArgs = db.BuildSimpleWhereClause(map[string]any{"ps.project_id": dbProject.ID}, len(joinArgs))
12✔
160
        var dbCommitments []db.ProjectCommitment
12✔
161
        _, err = p.DB.Select(&dbCommitments, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...)...)
12✔
162
        if respondwith.ErrorText(w, err) {
12✔
163
                return
×
164
        }
×
165

166
        // render response
167
        result := make([]limesresources.Commitment, 0, len(dbCommitments))
12✔
168
        for _, c := range dbCommitments {
26✔
169
                loc, exists := azResourceLocationsByID[c.AZResourceID]
14✔
170
                if !exists {
14✔
171
                        // defense in depth (the DB should not change that much between those two queries above)
×
172
                        continue
×
173
                }
174
                serviceInfo := core.InfoForService(serviceInfos, loc.ServiceType)
14✔
175
                resInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
14✔
176
                result = append(result, p.convertCommitmentToDisplayForm(c, loc, token, resInfo.Unit))
14✔
177
        }
178

179
        respondwith.JSON(w, http.StatusOK, map[string]any{"commitments": result})
12✔
180
}
181

182
func (p *v1Provider) convertCommitmentToDisplayForm(c db.ProjectCommitment, loc core.AZResourceLocation, token *gopherpolicy.Token, unit limes.Unit) limesresources.Commitment {
59✔
183
        apiIdentity := p.Cluster.BehaviorForResource(loc.ServiceType, loc.ResourceName).IdentityInV1API
59✔
184
        return limesresources.Commitment{
59✔
185
                ID:               int64(c.ID),
59✔
186
                UUID:             string(c.UUID),
59✔
187
                ServiceType:      apiIdentity.ServiceType,
59✔
188
                ResourceName:     apiIdentity.Name,
59✔
189
                AvailabilityZone: loc.AvailabilityZone,
59✔
190
                Amount:           c.Amount,
59✔
191
                Unit:             unit,
59✔
192
                Duration:         c.Duration,
59✔
193
                CreatedAt:        limes.UnixEncodedTime{Time: c.CreatedAt},
59✔
194
                CreatorUUID:      c.CreatorUUID,
59✔
195
                CreatorName:      c.CreatorName,
59✔
196
                CanBeDeleted:     p.canDeleteCommitment(token, c),
59✔
197
                ConfirmBy:        options.Map(c.ConfirmBy, intoUnixEncodedTime).AsPointer(),
59✔
198
                ConfirmedAt:      options.Map(c.ConfirmedAt, intoUnixEncodedTime).AsPointer(),
59✔
199
                ExpiresAt:        limes.UnixEncodedTime{Time: c.ExpiresAt},
59✔
200
                TransferStatus:   c.TransferStatus,
59✔
201
                TransferToken:    c.TransferToken.AsPointer(),
59✔
202
                NotifyOnConfirm:  c.NotifyOnConfirm,
59✔
203
                WasRenewed:       c.RenewContextJSON.IsSome(),
59✔
204
        }
59✔
205
}
59✔
206

207
// parseAndValidateCommitmentRequest parses and validates the request body for a commitment creation or confirmation.
208
// This function in its current form should only be used if the serviceInfo is not necessary to be used outside
209
// of this validation to avoid unnecessary database queries.
210
func (p *v1Provider) parseAndValidateCommitmentRequest(w http.ResponseWriter, r *http.Request, dbDomain db.Domain) (*limesresources.CommitmentRequest, *core.AZResourceLocation, *core.ScopedCommitmentBehavior) {
46✔
211
        // parse request
46✔
212
        var parseTarget struct {
46✔
213
                Request limesresources.CommitmentRequest `json:"commitment"`
46✔
214
        }
46✔
215
        if !RequireJSON(w, r, &parseTarget) {
47✔
216
                return nil, nil, nil
1✔
217
        }
1✔
218
        req := parseTarget.Request
45✔
219

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

261
        loc := core.AZResourceLocation{
35✔
262
                ServiceType:      dbServiceType,
35✔
263
                ResourceName:     dbResourceName,
35✔
264
                AvailabilityZone: req.AvailabilityZone,
35✔
265
        }
35✔
266
        return &req, &loc, &behavior
35✔
267
}
268

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

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

7✔
306
        // commitments can never be confirmed immediately if we are before the min_confirm_date
7✔
307
        now := p.timeNow()
7✔
308
        if !behavior.CanConfirmCommitmentsAt(now) {
8✔
309
                respondwith.JSON(w, http.StatusOK, map[string]bool{"result": false})
1✔
310
                return
1✔
311
        }
1✔
312

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

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

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

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

371
        // we want to validate committable capacity in the same transaction that creates the commitment
372
        tx, err := p.DB.Begin()
25✔
373
        if respondwith.ErrorText(w, err) {
25✔
374
                return
×
375
        }
×
376
        defer sqlext.RollbackUnlessCommitted(tx)
25✔
377

25✔
378
        // prepare commitment
25✔
379
        confirmBy := options.Map(options.FromPointer(req.ConfirmBy), fromUnixEncodedTime)
25✔
380
        creationContext := db.CommitmentWorkflowContext{Reason: db.CommitmentReasonCreate}
25✔
381
        buf, err := json.Marshal(creationContext)
25✔
382
        if respondwith.ErrorText(w, err) {
25✔
383
                return
×
384
        }
×
385
        dbCommitment := db.ProjectCommitment{
25✔
386
                UUID:                p.generateProjectCommitmentUUID(),
25✔
387
                AZResourceID:        azResourceID,
25✔
388
                Amount:              req.Amount,
25✔
389
                Duration:            req.Duration,
25✔
390
                CreatedAt:           now,
25✔
391
                CreatorUUID:         token.UserUUID(),
25✔
392
                CreatorName:         fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
25✔
393
                ConfirmBy:           confirmBy,
25✔
394
                ConfirmedAt:         None[time.Time](), // may be set below
25✔
395
                ExpiresAt:           req.Duration.AddTo(confirmBy.UnwrapOr(now)),
25✔
396
                CreationContextJSON: json.RawMessage(buf),
25✔
397
        }
25✔
398
        if req.NotifyOnConfirm && req.ConfirmBy == nil {
26✔
399
                http.Error(w, "notification on confirm cannot be set for commitments with immediate confirmation", http.StatusConflict)
1✔
400
                return
1✔
401
        }
1✔
402
        dbCommitment.NotifyOnConfirm = req.NotifyOnConfirm
24✔
403

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

420
        // create commitment
421
        err = tx.Insert(&dbCommitment)
24✔
422
        if respondwith.ErrorText(w, err) {
24✔
423
                return
×
424
        }
×
425
        err = tx.Commit()
24✔
426
        if respondwith.ErrorText(w, err) {
24✔
427
                return
×
428
        }
×
429
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
24✔
430
        if respondwith.ErrorText(w, err) {
24✔
NEW
431
                return
×
NEW
432
        }
×
433
        serviceInfo, ok := maybeServiceInfo.Unpack()
24✔
434
        if !ok {
24✔
NEW
435
                http.Error(w, "service not found", http.StatusNotFound)
×
NEW
436
                return
×
NEW
437
        }
×
438
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
24✔
439
        commitment := p.convertCommitmentToDisplayForm(dbCommitment, *loc, token, resourceInfo.Unit)
24✔
440
        p.auditor.Record(audittools.Event{
24✔
441
                Time:       now,
24✔
442
                Request:    r,
24✔
443
                User:       token,
24✔
444
                ReasonCode: http.StatusCreated,
24✔
445
                Action:     cadf.CreateAction,
24✔
446
                Target: commitmentEventTarget{
24✔
447
                        DomainID:        dbDomain.UUID,
24✔
448
                        DomainName:      dbDomain.Name,
24✔
449
                        ProjectID:       dbProject.UUID,
24✔
450
                        ProjectName:     dbProject.Name,
24✔
451
                        Commitments:     []limesresources.Commitment{commitment},
24✔
452
                        WorkflowContext: Some(creationContext),
24✔
453
                },
24✔
454
        })
24✔
455

24✔
456
        // if the commitment is immediately confirmed, trigger a capacity scrape in
24✔
457
        // order to ApplyComputedProjectQuotas based on the new commitment
24✔
458
        if dbCommitment.ConfirmedAt.IsSome() {
42✔
459
                _, err := p.DB.Exec(`UPDATE cluster_services SET next_scrape_at = $1 WHERE type = $2`, now, loc.ServiceType)
18✔
460
                if respondwith.ErrorText(w, err) {
18✔
461
                        return
×
462
                }
×
463
        }
464

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

471
        respondwith.JSON(w, http.StatusCreated, map[string]any{"commitment": commitment})
24✔
472
}
473

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

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

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

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

538
        // Start transaction for creating new commitment and marking merged commitments as superseded
539
        tx, err := p.DB.Begin()
1✔
540
        if respondwith.ErrorText(w, err) {
1✔
541
                return
×
542
        }
×
543
        defer sqlext.RollbackUnlessCommitted(tx)
1✔
544

1✔
545
        // Create merged template
1✔
546
        now := p.timeNow()
1✔
547
        dbMergedCommitment := db.ProjectCommitment{
1✔
548
                UUID:         p.generateProjectCommitmentUUID(),
1✔
549
                AZResourceID: azResourceID,
1✔
550
                Amount:       0,                                   // overwritten below
1✔
551
                Duration:     limesresources.CommitmentDuration{}, // overwritten below
1✔
552
                CreatedAt:    now,
1✔
553
                CreatorUUID:  token.UserUUID(),
1✔
554
                CreatorName:  fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
1✔
555
                ConfirmedAt:  Some(now),
1✔
556
                ExpiresAt:    time.Time{}, // overwritten below
1✔
557
                State:        db.CommitmentStateActive,
1✔
558
        }
1✔
559

1✔
560
        // Fill amount and latest expiration date
1✔
561
        for _, dbCommitment := range dbCommitments {
3✔
562
                dbMergedCommitment.Amount += dbCommitment.Amount
2✔
563
                if dbCommitment.ExpiresAt.After(dbMergedCommitment.ExpiresAt) {
4✔
564
                        dbMergedCommitment.ExpiresAt = dbCommitment.ExpiresAt
2✔
565
                        dbMergedCommitment.Duration = dbCommitment.Duration
2✔
566
                }
2✔
567
        }
568

569
        // Fill workflow context
570
        creationContext := db.CommitmentWorkflowContext{
1✔
571
                Reason:                 db.CommitmentReasonMerge,
1✔
572
                RelatedCommitmentIDs:   commitmentIDs,
1✔
573
                RelatedCommitmentUUIDs: commitmentUUIDs,
1✔
574
        }
1✔
575
        buf, err := json.Marshal(creationContext)
1✔
576
        if respondwith.ErrorText(w, err) {
1✔
577
                return
×
578
        }
×
579
        dbMergedCommitment.CreationContextJSON = json.RawMessage(buf)
1✔
580

1✔
581
        // Insert into database
1✔
582
        err = tx.Insert(&dbMergedCommitment)
1✔
583
        if respondwith.ErrorText(w, err) {
1✔
584
                return
×
585
        }
×
586

587
        // Mark merged commits as superseded
588
        supersedeContext := db.CommitmentWorkflowContext{
1✔
589
                Reason:                 db.CommitmentReasonMerge,
1✔
590
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbMergedCommitment.ID},
1✔
591
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbMergedCommitment.UUID},
1✔
592
        }
1✔
593
        buf, err = json.Marshal(supersedeContext)
1✔
594
        if respondwith.ErrorText(w, err) {
1✔
595
                return
×
596
        }
×
597
        for _, dbCommitment := range dbCommitments {
3✔
598
                dbCommitment.SupersededAt = Some(now)
2✔
599
                dbCommitment.SupersedeContextJSON = Some(json.RawMessage(buf))
2✔
600
                dbCommitment.State = db.CommitmentStateSuperseded
2✔
601
                _, err = tx.Update(&dbCommitment)
2✔
602
                if respondwith.ErrorText(w, err) {
2✔
603
                        return
×
604
                }
×
605
        }
606

607
        err = tx.Commit()
1✔
608
        if respondwith.ErrorText(w, err) {
1✔
609
                return
×
610
        }
×
611

612
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
1✔
613
        if respondwith.ErrorText(w, err) {
1✔
NEW
614
                return
×
NEW
615
        }
×
616
        serviceInfo, ok := maybeServiceInfo.Unpack()
1✔
617
        if !ok {
1✔
NEW
618
                http.Error(w, "service not found", http.StatusNotFound)
×
NEW
619
                return
×
NEW
620
        }
×
621
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
1✔
622

1✔
623
        c := p.convertCommitmentToDisplayForm(dbMergedCommitment, loc, token, resourceInfo.Unit)
1✔
624
        auditEvent := commitmentEventTarget{
1✔
625
                DomainID:        dbDomain.UUID,
1✔
626
                DomainName:      dbDomain.Name,
1✔
627
                ProjectID:       dbProject.UUID,
1✔
628
                ProjectName:     dbProject.Name,
1✔
629
                Commitments:     []limesresources.Commitment{c},
1✔
630
                WorkflowContext: Some(creationContext),
1✔
631
        }
1✔
632
        p.auditor.Record(audittools.Event{
1✔
633
                Time:       p.timeNow(),
1✔
634
                Request:    r,
1✔
635
                User:       token,
1✔
636
                ReasonCode: http.StatusAccepted,
1✔
637
                Action:     cadf.UpdateAction,
1✔
638
                Target:     auditEvent,
1✔
639
        })
1✔
640

1✔
641
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
642
}
643

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

647
// RenewProjectCommitments handles POST /v1/domains/:domain_id/projects/:project_id/commitments/:id/renew.
648
func (p *v1Provider) RenewProjectCommitments(w http.ResponseWriter, r *http.Request) {
6✔
649
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id/renew")
6✔
650
        token := p.CheckToken(r)
6✔
651
        if !token.Require(w, "project:edit") {
6✔
652
                return
×
653
        }
×
654
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
655
        if dbDomain == nil {
6✔
656
                return
×
657
        }
×
658
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
659
        if dbProject == nil {
6✔
660
                return
×
661
        }
×
662

663
        // Load commitment
664
        var dbCommitment db.ProjectCommitment
6✔
665
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
6✔
666
        if errors.Is(err, sql.ErrNoRows) {
6✔
667
                http.Error(w, "no such commitment", http.StatusNotFound)
×
668
                return
×
669
        } else if respondwith.ErrorText(w, err) {
6✔
670
                return
×
671
        }
×
672
        now := p.timeNow()
6✔
673

6✔
674
        // Check if commitment can be renewed
6✔
675
        var errs errext.ErrorSet
6✔
676
        if dbCommitment.State != db.CommitmentStateActive {
7✔
677
                errs.Addf("invalid state %q", dbCommitment.State)
1✔
678
        } else if now.After(dbCommitment.ExpiresAt) {
7✔
679
                errs.Addf("invalid state %q", db.CommitmentStateExpired)
1✔
680
        }
1✔
681
        if now.Before(dbCommitment.ExpiresAt.Add(-commitmentRenewalPeriod)) {
7✔
682
                errs.Addf("renewal attempt too early")
1✔
683
        }
1✔
684
        if dbCommitment.RenewContextJSON.IsSome() {
7✔
685
                errs.Addf("already renewed")
1✔
686
        }
1✔
687

688
        if !errs.IsEmpty() {
10✔
689
                msg := "cannot renew this commitment: " + errs.Join(", ")
4✔
690
                http.Error(w, msg, http.StatusConflict)
4✔
691
                return
4✔
692
        }
4✔
693

694
        // Create renewed commitment
695
        tx, err := p.DB.Begin()
2✔
696
        if respondwith.ErrorText(w, err) {
2✔
697
                return
×
698
        }
×
699
        defer sqlext.RollbackUnlessCommitted(tx)
2✔
700

2✔
701
        var loc core.AZResourceLocation
2✔
702
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
2✔
703
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
2✔
704
        if errors.Is(err, sql.ErrNoRows) {
2✔
705
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
706
                return
×
707
        } else if respondwith.ErrorText(w, err) {
2✔
708
                return
×
709
        }
×
710

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

2✔
734
        err = tx.Insert(&dbRenewedCommitment)
2✔
735
        if respondwith.ErrorText(w, err) {
2✔
736
                return
×
737
        }
×
738

739
        renewContext := db.CommitmentWorkflowContext{
2✔
740
                Reason:                 db.CommitmentReasonRenew,
2✔
741
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbRenewedCommitment.ID},
2✔
742
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbRenewedCommitment.UUID},
2✔
743
        }
2✔
744
        buf, err = json.Marshal(renewContext)
2✔
745
        if respondwith.ErrorText(w, err) {
2✔
746
                return
×
747
        }
×
748
        dbCommitment.RenewContextJSON = Some(json.RawMessage(buf))
2✔
749
        _, err = tx.Update(&dbCommitment)
2✔
750
        if respondwith.ErrorText(w, err) {
2✔
751
                return
×
752
        }
×
753

754
        err = tx.Commit()
2✔
755
        if respondwith.ErrorText(w, err) {
2✔
756
                return
×
757
        }
×
758

759
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
2✔
760
        if respondwith.ErrorText(w, err) {
2✔
NEW
761
                return
×
NEW
762
        }
×
763
        serviceInfo, ok := maybeServiceInfo.Unpack()
2✔
764
        if !ok {
2✔
NEW
765
                http.Error(w, "service not found", http.StatusNotFound)
×
NEW
766
                return
×
NEW
767
        }
×
768
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
2✔
769

2✔
770
        // Create resultset and auditlogs
2✔
771
        c := p.convertCommitmentToDisplayForm(dbRenewedCommitment, loc, token, resourceInfo.Unit)
2✔
772
        auditEvent := commitmentEventTarget{
2✔
773
                DomainID:        dbDomain.UUID,
2✔
774
                DomainName:      dbDomain.Name,
2✔
775
                ProjectID:       dbProject.UUID,
2✔
776
                ProjectName:     dbProject.Name,
2✔
777
                Commitments:     []limesresources.Commitment{c},
2✔
778
                WorkflowContext: Some(creationContext),
2✔
779
        }
2✔
780

2✔
781
        p.auditor.Record(audittools.Event{
2✔
782
                Time:       p.timeNow(),
2✔
783
                Request:    r,
2✔
784
                User:       token,
2✔
785
                ReasonCode: http.StatusAccepted,
2✔
786
                Action:     cadf.UpdateAction,
2✔
787
                Target:     auditEvent,
2✔
788
        })
2✔
789

2✔
790
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
791
}
792

793
// DeleteProjectCommitment handles DELETE /v1/domains/:domain_id/projects/:project_id/commitments/:id.
794
func (p *v1Provider) DeleteProjectCommitment(w http.ResponseWriter, r *http.Request) {
8✔
795
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id")
8✔
796
        token := p.CheckToken(r)
8✔
797
        if !token.Require(w, "project:edit") { // NOTE: There is a more specific AuthZ check further down below.
8✔
798
                return
×
799
        }
×
800
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
801
        if dbDomain == nil {
9✔
802
                return
1✔
803
        }
1✔
804
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
7✔
805
        if dbProject == nil {
8✔
806
                return
1✔
807
        }
1✔
808

809
        // load commitment
810
        var dbCommitment db.ProjectCommitment
6✔
811
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
6✔
812
        if errors.Is(err, sql.ErrNoRows) {
7✔
813
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
814
                return
1✔
815
        } else if respondwith.ErrorText(w, err) {
6✔
816
                return
×
817
        }
×
818
        var loc core.AZResourceLocation
5✔
819
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
5✔
820
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
5✔
821
        if errors.Is(err, sql.ErrNoRows) {
5✔
822
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
823
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
824
                return
×
825
        } else if respondwith.ErrorText(w, err) {
5✔
826
                return
×
827
        }
×
828

829
        // check authorization for this specific commitment
830
        if !p.canDeleteCommitment(token, dbCommitment) {
6✔
831
                http.Error(w, "Forbidden", http.StatusForbidden)
1✔
832
                return
1✔
833
        }
1✔
834

835
        // perform deletion
836
        _, err = p.DB.Delete(&dbCommitment)
4✔
837
        if respondwith.ErrorText(w, err) {
4✔
838
                return
×
839
        }
×
840
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
4✔
841
        if respondwith.ErrorText(w, err) {
4✔
NEW
842
                return
×
NEW
843
        }
×
844
        serviceInfo, ok := maybeServiceInfo.Unpack()
4✔
845
        if !ok {
4✔
NEW
846
                http.Error(w, "service not found", http.StatusNotFound)
×
NEW
847
                return
×
NEW
848
        }
×
849
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
4✔
850
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
4✔
851
        p.auditor.Record(audittools.Event{
4✔
852
                Time:       p.timeNow(),
4✔
853
                Request:    r,
4✔
854
                User:       token,
4✔
855
                ReasonCode: http.StatusNoContent,
4✔
856
                Action:     cadf.DeleteAction,
4✔
857
                Target: commitmentEventTarget{
4✔
858
                        DomainID:    dbDomain.UUID,
4✔
859
                        DomainName:  dbDomain.Name,
4✔
860
                        ProjectID:   dbProject.UUID,
4✔
861
                        ProjectName: dbProject.Name,
4✔
862
                        Commitments: []limesresources.Commitment{c},
4✔
863
                },
4✔
864
        })
4✔
865

4✔
866
        w.WriteHeader(http.StatusNoContent)
4✔
867
}
868

869
func (p *v1Provider) canDeleteCommitment(token *gopherpolicy.Token, commitment db.ProjectCommitment) bool {
64✔
870
        // up to 24 hours after creation of fresh commitments, future commitments can still be deleted by their creators
64✔
871
        if commitment.State == db.CommitmentStatePlanned || commitment.State == db.CommitmentStatePending || commitment.State == db.CommitmentStateActive {
128✔
872
                var creationContext db.CommitmentWorkflowContext
64✔
873
                err := json.Unmarshal(commitment.CreationContextJSON, &creationContext)
64✔
874
                if err == nil && creationContext.Reason == db.CommitmentReasonCreate && p.timeNow().Before(commitment.CreatedAt.Add(24*time.Hour)) {
104✔
875
                        if token.Check("project:edit") {
80✔
876
                                return true
40✔
877
                        }
40✔
878
                }
879
        }
880

881
        // afterwards, a more specific permission is required to delete it
882
        //
883
        // This protects cloud admins making capacity planning decisions based on future commitments
884
        // from having their forecasts ruined by project admins suffering from buyer's remorse.
885
        return token.Check("project:uncommit")
24✔
886
}
887

888
// StartCommitmentTransfer handles POST /v1/domains/:id/projects/:id/commitments/:id/start-transfer
889
func (p *v1Provider) StartCommitmentTransfer(w http.ResponseWriter, r *http.Request) {
8✔
890
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id/start-transfer")
8✔
891
        token := p.CheckToken(r)
8✔
892
        if !token.Require(w, "project:edit") {
8✔
893
                return
×
894
        }
×
895
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
896
        if dbDomain == nil {
8✔
897
                return
×
898
        }
×
899
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
8✔
900
        if dbProject == nil {
8✔
901
                return
×
902
        }
×
903
        // TODO: eventually migrate this struct into go-api-declarations
904
        var parseTarget struct {
8✔
905
                Request struct {
8✔
906
                        Amount         uint64                                  `json:"amount"`
8✔
907
                        TransferStatus limesresources.CommitmentTransferStatus `json:"transfer_status,omitempty"`
8✔
908
                } `json:"commitment"`
8✔
909
        }
8✔
910
        if !RequireJSON(w, r, &parseTarget) {
8✔
911
                return
×
912
        }
×
913
        req := parseTarget.Request
8✔
914

8✔
915
        if req.TransferStatus != limesresources.CommitmentTransferStatusUnlisted && req.TransferStatus != limesresources.CommitmentTransferStatusPublic {
8✔
916
                http.Error(w, fmt.Sprintf("Invalid transfer_status code. Must be %s or %s.", limesresources.CommitmentTransferStatusUnlisted, limesresources.CommitmentTransferStatusPublic), http.StatusBadRequest)
×
917
                return
×
918
        }
×
919

920
        if req.Amount <= 0 {
9✔
921
                http.Error(w, "delivered amount needs to be a positive value.", http.StatusBadRequest)
1✔
922
                return
1✔
923
        }
1✔
924

925
        // load commitment
926
        var dbCommitment db.ProjectCommitment
7✔
927
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
7✔
928
        if errors.Is(err, sql.ErrNoRows) {
7✔
929
                http.Error(w, "no such commitment", http.StatusNotFound)
×
930
                return
×
931
        } else if respondwith.ErrorText(w, err) {
7✔
932
                return
×
933
        }
×
934

935
        // Mark whole commitment or a newly created, splitted one as transferrable.
936
        tx, err := p.DB.Begin()
7✔
937
        if respondwith.ErrorText(w, err) {
7✔
938
                return
×
939
        }
×
940
        defer sqlext.RollbackUnlessCommitted(tx)
7✔
941
        transferToken := p.generateTransferToken()
7✔
942

7✔
943
        // Deny requests with a greater amount than the commitment.
7✔
944
        if req.Amount > dbCommitment.Amount {
8✔
945
                http.Error(w, "delivered amount exceeds the commitment amount.", http.StatusBadRequest)
1✔
946
                return
1✔
947
        }
1✔
948

949
        if req.Amount == dbCommitment.Amount {
10✔
950
                dbCommitment.TransferStatus = req.TransferStatus
4✔
951
                dbCommitment.TransferToken = Some(transferToken)
4✔
952
                _, err = tx.Update(&dbCommitment)
4✔
953
                if respondwith.ErrorText(w, err) {
4✔
954
                        return
×
955
                }
×
956
        } else {
2✔
957
                now := p.timeNow()
2✔
958
                transferAmount := req.Amount
2✔
959
                remainingAmount := dbCommitment.Amount - req.Amount
2✔
960
                transferCommitment, err := p.buildSplitCommitment(dbCommitment, transferAmount)
2✔
961
                if respondwith.ErrorText(w, err) {
2✔
962
                        return
×
963
                }
×
964
                transferCommitment.TransferStatus = req.TransferStatus
2✔
965
                transferCommitment.TransferToken = Some(transferToken)
2✔
966
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
2✔
967
                if respondwith.ErrorText(w, err) {
2✔
968
                        return
×
969
                }
×
970
                err = tx.Insert(&transferCommitment)
2✔
971
                if respondwith.ErrorText(w, err) {
2✔
972
                        return
×
973
                }
×
974
                err = tx.Insert(&remainingCommitment)
2✔
975
                if respondwith.ErrorText(w, err) {
2✔
976
                        return
×
977
                }
×
978
                supersedeContext := db.CommitmentWorkflowContext{
2✔
979
                        Reason:                 db.CommitmentReasonSplit,
2✔
980
                        RelatedCommitmentIDs:   []db.ProjectCommitmentID{transferCommitment.ID, remainingCommitment.ID},
2✔
981
                        RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{transferCommitment.UUID, remainingCommitment.UUID},
2✔
982
                }
2✔
983
                buf, err := json.Marshal(supersedeContext)
2✔
984
                if respondwith.ErrorText(w, err) {
2✔
985
                        return
×
986
                }
×
987
                dbCommitment.State = db.CommitmentStateSuperseded
2✔
988
                dbCommitment.SupersededAt = Some(now)
2✔
989
                dbCommitment.SupersedeContextJSON = Some(json.RawMessage(buf))
2✔
990
                _, err = tx.Update(&dbCommitment)
2✔
991
                if respondwith.ErrorText(w, err) {
2✔
992
                        return
×
993
                }
×
994
                dbCommitment = transferCommitment
2✔
995
        }
996
        err = tx.Commit()
6✔
997
        if respondwith.ErrorText(w, err) {
6✔
998
                return
×
999
        }
×
1000

1001
        var loc core.AZResourceLocation
6✔
1002
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
6✔
1003
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
6✔
1004
        if errors.Is(err, sql.ErrNoRows) {
6✔
1005
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1006
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1007
                return
×
1008
        } else if respondwith.ErrorText(w, err) {
6✔
1009
                return
×
1010
        }
×
1011

1012
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
6✔
1013
        if respondwith.ErrorText(w, err) {
6✔
NEW
1014
                return
×
NEW
1015
        }
×
1016
        serviceInfo, ok := maybeServiceInfo.Unpack()
6✔
1017
        if !ok {
6✔
NEW
1018
                http.Error(w, "service not found", http.StatusNotFound)
×
NEW
1019
                return
×
NEW
1020
        }
×
1021
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
6✔
1022
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
6✔
1023
        if respondwith.ErrorText(w, err) {
6✔
NEW
1024
                return
×
NEW
1025
        }
×
1026
        p.auditor.Record(audittools.Event{
6✔
1027
                Time:       p.timeNow(),
6✔
1028
                Request:    r,
6✔
1029
                User:       token,
6✔
1030
                ReasonCode: http.StatusAccepted,
6✔
1031
                Action:     cadf.UpdateAction,
6✔
1032
                Target: commitmentEventTarget{
6✔
1033
                        DomainID:    dbDomain.UUID,
6✔
1034
                        DomainName:  dbDomain.Name,
6✔
1035
                        ProjectID:   dbProject.UUID,
6✔
1036
                        ProjectName: dbProject.Name,
6✔
1037
                        Commitments: []limesresources.Commitment{c},
6✔
1038
                },
6✔
1039
        })
6✔
1040
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
6✔
1041
}
1042

1043
func (p *v1Provider) buildSplitCommitment(dbCommitment db.ProjectCommitment, amount uint64) (db.ProjectCommitment, error) {
5✔
1044
        now := p.timeNow()
5✔
1045
        creationContext := db.CommitmentWorkflowContext{
5✔
1046
                Reason:                 db.CommitmentReasonSplit,
5✔
1047
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
5✔
1048
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
5✔
1049
        }
5✔
1050
        buf, err := json.Marshal(creationContext)
5✔
1051
        if err != nil {
5✔
1052
                return db.ProjectCommitment{}, err
×
1053
        }
×
1054
        return db.ProjectCommitment{
5✔
1055
                UUID:                p.generateProjectCommitmentUUID(),
5✔
1056
                AZResourceID:        dbCommitment.AZResourceID,
5✔
1057
                Amount:              amount,
5✔
1058
                Duration:            dbCommitment.Duration,
5✔
1059
                CreatedAt:           now,
5✔
1060
                CreatorUUID:         dbCommitment.CreatorUUID,
5✔
1061
                CreatorName:         dbCommitment.CreatorName,
5✔
1062
                ConfirmBy:           dbCommitment.ConfirmBy,
5✔
1063
                ConfirmedAt:         dbCommitment.ConfirmedAt,
5✔
1064
                ExpiresAt:           dbCommitment.ExpiresAt,
5✔
1065
                CreationContextJSON: json.RawMessage(buf),
5✔
1066
                State:               dbCommitment.State,
5✔
1067
        }, nil
5✔
1068
}
1069

1070
func (p *v1Provider) buildConvertedCommitment(dbCommitment db.ProjectCommitment, azResourceID db.ProjectAZResourceID, amount uint64) (db.ProjectCommitment, error) {
2✔
1071
        now := p.timeNow()
2✔
1072
        creationContext := db.CommitmentWorkflowContext{
2✔
1073
                Reason:                 db.CommitmentReasonConvert,
2✔
1074
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1075
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
2✔
1076
        }
2✔
1077
        buf, err := json.Marshal(creationContext)
2✔
1078
        if err != nil {
2✔
1079
                return db.ProjectCommitment{}, err
×
1080
        }
×
1081
        return db.ProjectCommitment{
2✔
1082
                UUID:                p.generateProjectCommitmentUUID(),
2✔
1083
                AZResourceID:        azResourceID,
2✔
1084
                Amount:              amount,
2✔
1085
                Duration:            dbCommitment.Duration,
2✔
1086
                CreatedAt:           now,
2✔
1087
                CreatorUUID:         dbCommitment.CreatorUUID,
2✔
1088
                CreatorName:         dbCommitment.CreatorName,
2✔
1089
                ConfirmBy:           dbCommitment.ConfirmBy,
2✔
1090
                ConfirmedAt:         dbCommitment.ConfirmedAt,
2✔
1091
                ExpiresAt:           dbCommitment.ExpiresAt,
2✔
1092
                CreationContextJSON: json.RawMessage(buf),
2✔
1093
                State:               dbCommitment.State,
2✔
1094
        }, nil
2✔
1095
}
1096

1097
// GetCommitmentByTransferToken handles GET /v1/commitments/{token}
1098
func (p *v1Provider) GetCommitmentByTransferToken(w http.ResponseWriter, r *http.Request) {
2✔
1099
        httpapi.IdentifyEndpoint(r, "/v1/commitments/:token")
2✔
1100
        token := p.CheckToken(r)
2✔
1101
        if !token.Require(w, "cluster:show_basic") {
2✔
1102
                return
×
1103
        }
×
1104
        transferToken := mux.Vars(r)["token"]
2✔
1105

2✔
1106
        // The token column is a unique key, so we expect only one result.
2✔
1107
        var dbCommitment db.ProjectCommitment
2✔
1108
        err := p.DB.SelectOne(&dbCommitment, findCommitmentByTransferToken, transferToken)
2✔
1109
        if errors.Is(err, sql.ErrNoRows) {
3✔
1110
                http.Error(w, "no matching commitment found.", http.StatusNotFound)
1✔
1111
                return
1✔
1112
        } else if respondwith.ErrorText(w, err) {
2✔
1113
                return
×
1114
        }
×
1115

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

1127
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
1✔
1128
        if respondwith.ErrorText(w, err) {
1✔
NEW
1129
                return
×
NEW
1130
        }
×
1131
        serviceInfo, ok := maybeServiceInfo.Unpack()
1✔
1132
        if !ok {
1✔
NEW
1133
                http.Error(w, "service not found", http.StatusNotFound)
×
NEW
1134
                return
×
NEW
1135
        }
×
1136
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
1✔
1137
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
1✔
1138
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
1139
}
1140

1141
// TransferCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/transfer-commitment/{id}?token={token}
1142
func (p *v1Provider) TransferCommitment(w http.ResponseWriter, r *http.Request) {
5✔
1143
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/transfer-commitment/:id")
5✔
1144
        token := p.CheckToken(r)
5✔
1145
        if !token.Require(w, "project:edit") {
5✔
1146
                return
×
1147
        }
×
1148
        transferToken := r.Header.Get("Transfer-Token")
5✔
1149
        if transferToken == "" {
6✔
1150
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
1✔
1151
                return
1✔
1152
        }
1✔
1153
        commitmentID := mux.Vars(r)["id"]
4✔
1154
        if commitmentID == "" {
4✔
1155
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1156
                return
×
1157
        }
×
1158
        dbDomain := p.FindDomainFromRequest(w, r)
4✔
1159
        if dbDomain == nil {
4✔
1160
                return
×
1161
        }
×
1162
        targetProject := p.FindProjectFromRequest(w, r, dbDomain)
4✔
1163
        if targetProject == nil {
4✔
1164
                return
×
1165
        }
×
1166

1167
        // find commitment by transfer_token
1168
        var dbCommitment db.ProjectCommitment
4✔
1169
        err := p.DB.SelectOne(&dbCommitment, getCommitmentWithMatchingTransferTokenQuery, commitmentID, transferToken)
4✔
1170
        if errors.Is(err, sql.ErrNoRows) {
5✔
1171
                http.Error(w, "no matching commitment found", http.StatusNotFound)
1✔
1172
                return
1✔
1173
        } else if respondwith.ErrorText(w, err) {
4✔
1174
                return
×
1175
        }
×
1176

1177
        var loc core.AZResourceLocation
3✔
1178
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
3✔
1179
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
3✔
1180
        if errors.Is(err, sql.ErrNoRows) {
3✔
1181
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1182
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1183
                return
×
1184
        } else if respondwith.ErrorText(w, err) {
3✔
1185
                return
×
1186
        }
×
1187

1188
        // get target service and AZ resource
1189
        var (
3✔
1190
                sourceResourceID   db.ProjectResourceID
3✔
1191
                targetResourceID   db.ProjectResourceID
3✔
1192
                targetAZResourceID db.ProjectAZResourceID
3✔
1193
        )
3✔
1194
        err = p.DB.QueryRow(findTargetAZResourceIDBySourceIDQuery, dbCommitment.AZResourceID, targetProject.ID).
3✔
1195
                Scan(&sourceResourceID, &targetResourceID, &targetAZResourceID)
3✔
1196
        if respondwith.ErrorText(w, err) {
3✔
1197
                return
×
1198
        }
×
1199

1200
        // validate that we have enough committable capacity on the receiving side
1201
        tx, err := p.DB.Begin()
3✔
1202
        if respondwith.ErrorText(w, err) {
3✔
1203
                return
×
1204
        }
×
1205
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1206
        ok, err := datamodel.CanMoveExistingCommitment(dbCommitment.Amount, loc, sourceResourceID, targetResourceID, p.Cluster, tx)
3✔
1207
        if respondwith.ErrorText(w, err) {
3✔
1208
                return
×
1209
        }
×
1210
        if !ok {
4✔
1211
                http.Error(w, "not enough committable capacity on the receiving side", http.StatusConflict)
1✔
1212
                return
1✔
1213
        }
1✔
1214

1215
        dbCommitment.TransferStatus = ""
2✔
1216
        dbCommitment.TransferToken = None[string]()
2✔
1217
        dbCommitment.AZResourceID = targetAZResourceID
2✔
1218
        _, err = tx.Update(&dbCommitment)
2✔
1219
        if respondwith.ErrorText(w, err) {
2✔
1220
                return
×
1221
        }
×
1222
        err = tx.Commit()
2✔
1223
        if respondwith.ErrorText(w, err) {
2✔
1224
                return
×
1225
        }
×
1226

1227
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
2✔
1228
        if respondwith.ErrorText(w, err) {
2✔
NEW
1229
                return
×
NEW
1230
        }
×
1231
        serviceInfo, ok := maybeServiceInfo.Unpack()
2✔
1232
        if !ok {
2✔
NEW
1233
                http.Error(w, "service not found", http.StatusNotFound)
×
NEW
1234
                return
×
NEW
1235
        }
×
1236
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
2✔
1237
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
2✔
1238
        p.auditor.Record(audittools.Event{
2✔
1239
                Time:       p.timeNow(),
2✔
1240
                Request:    r,
2✔
1241
                User:       token,
2✔
1242
                ReasonCode: http.StatusAccepted,
2✔
1243
                Action:     cadf.UpdateAction,
2✔
1244
                Target: commitmentEventTarget{
2✔
1245
                        DomainID:    dbDomain.UUID,
2✔
1246
                        DomainName:  dbDomain.Name,
2✔
1247
                        ProjectID:   targetProject.UUID,
2✔
1248
                        ProjectName: targetProject.Name,
2✔
1249
                        Commitments: []limesresources.Commitment{c},
2✔
1250
                },
2✔
1251
        })
2✔
1252

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

1256
// GetCommitmentConversion handles GET /v1/commitment-conversion/{service_type}/{resource_name}
1257
func (p *v1Provider) GetCommitmentConversions(w http.ResponseWriter, r *http.Request) {
2✔
1258
        httpapi.IdentifyEndpoint(r, "/v1/commitment-conversion/:service_type/:resource_name")
2✔
1259
        token := p.CheckToken(r)
2✔
1260
        if !token.Require(w, "cluster:show_basic") {
2✔
1261
                return
×
1262
        }
×
1263

1264
        // TODO v2 API: This endpoint should be project-scoped in order to make it
1265
        // easier to select the correct domain scope for the CommitmentBehavior.
1266
        forTokenScope := func(behavior core.CommitmentBehavior) core.ScopedCommitmentBehavior {
12✔
1267
                name := cmp.Or(token.ProjectScopeDomainName(), token.DomainScopeName(), "")
10✔
1268
                if name != "" {
20✔
1269
                        return behavior.ForDomain(name)
10✔
1270
                }
10✔
1271
                return behavior.ForCluster()
×
1272
        }
1273

1274
        // validate request
1275
        vars := mux.Vars(r)
2✔
1276
        serviceInfos, err := p.Cluster.AllServiceInfos()
2✔
1277
        if respondwith.ErrorText(w, err) {
2✔
NEW
1278
                return
×
NEW
1279
        }
×
1280

1281
        nm := core.BuildResourceNameMapping(p.Cluster, serviceInfos)
2✔
1282
        sourceServiceType, sourceResourceName, exists := nm.MapFromV1API(
2✔
1283
                limes.ServiceType(vars["service_type"]),
2✔
1284
                limesresources.ResourceName(vars["resource_name"]),
2✔
1285
        )
2✔
1286
        if !exists {
2✔
1287
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", vars["service_type"], vars["resource_name"])
×
1288
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1289
                return
×
1290
        }
×
1291
        sourceBehavior := forTokenScope(p.Cluster.CommitmentBehaviorForResource(sourceServiceType, sourceResourceName))
2✔
1292

2✔
1293
        serviceInfo := core.InfoForService(serviceInfos, sourceServiceType)
2✔
1294
        sourceResInfo := core.InfoForResource(serviceInfo, sourceResourceName)
2✔
1295

2✔
1296
        // enumerate possible conversions
2✔
1297
        conversions := make([]limesresources.CommitmentConversionRule, 0)
2✔
1298
        if sourceBehavior.ConversionRule.IsSome() {
4✔
1299
                for _, targetServiceType := range slices.Sorted(maps.Keys(serviceInfos)) {
8✔
1300
                        for targetResourceName, targetResInfo := range serviceInfos[targetServiceType].Resources {
26✔
1301
                                if sourceServiceType == targetServiceType && sourceResourceName == targetResourceName {
22✔
1302
                                        continue
2✔
1303
                                }
1304
                                if sourceResInfo.Unit != targetResInfo.Unit {
28✔
1305
                                        continue
10✔
1306
                                }
1307

1308
                                targetBehavior := forTokenScope(p.Cluster.CommitmentBehaviorForResource(targetServiceType, targetResourceName))
8✔
1309
                                if rate, ok := sourceBehavior.GetConversionRateTo(targetBehavior).Unpack(); ok {
12✔
1310
                                        apiServiceType, apiResourceName, ok := nm.MapToV1API(targetServiceType, targetResourceName)
4✔
1311
                                        if ok {
8✔
1312
                                                conversions = append(conversions, limesresources.CommitmentConversionRule{
4✔
1313
                                                        FromAmount:     rate.FromAmount,
4✔
1314
                                                        ToAmount:       rate.ToAmount,
4✔
1315
                                                        TargetService:  apiServiceType,
4✔
1316
                                                        TargetResource: apiResourceName,
4✔
1317
                                                })
4✔
1318
                                        }
4✔
1319
                                }
1320
                        }
1321
                }
1322
        }
1323

1324
        // use a defined sorting to ensure deterministic behavior in tests
1325
        slices.SortFunc(conversions, func(lhs, rhs limesresources.CommitmentConversionRule) int {
5✔
1326
                result := strings.Compare(string(lhs.TargetService), string(rhs.TargetService))
3✔
1327
                if result != 0 {
5✔
1328
                        return result
2✔
1329
                }
2✔
1330
                return strings.Compare(string(lhs.TargetResource), string(rhs.TargetResource))
1✔
1331
        })
1332

1333
        respondwith.JSON(w, http.StatusOK, map[string]any{"conversions": conversions})
2✔
1334
}
1335

1336
// ConvertCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/convert
1337
func (p *v1Provider) ConvertCommitment(w http.ResponseWriter, r *http.Request) {
9✔
1338
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/convert")
9✔
1339
        token := p.CheckToken(r)
9✔
1340
        if !token.Require(w, "project:edit") {
9✔
1341
                return
×
1342
        }
×
1343
        commitmentID := mux.Vars(r)["commitment_id"]
9✔
1344
        if commitmentID == "" {
9✔
1345
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1346
                return
×
1347
        }
×
1348
        dbDomain := p.FindDomainFromRequest(w, r)
9✔
1349
        if dbDomain == nil {
9✔
1350
                return
×
1351
        }
×
1352
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
9✔
1353
        if dbProject == nil {
9✔
1354
                return
×
1355
        }
×
1356

1357
        // section: sourceBehavior
1358
        var dbCommitment db.ProjectCommitment
9✔
1359
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
9✔
1360
        if errors.Is(err, sql.ErrNoRows) {
10✔
1361
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
1362
                return
1✔
1363
        } else if respondwith.ErrorText(w, err) {
9✔
1364
                return
×
1365
        }
×
1366
        var sourceLoc core.AZResourceLocation
8✔
1367
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
8✔
1368
                Scan(&sourceLoc.ServiceType, &sourceLoc.ResourceName, &sourceLoc.AvailabilityZone)
8✔
1369
        if errors.Is(err, sql.ErrNoRows) {
8✔
1370
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1371
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1372
                return
×
1373
        } else if respondwith.ErrorText(w, err) {
8✔
1374
                return
×
1375
        }
×
1376
        sourceBehavior := p.Cluster.CommitmentBehaviorForResource(sourceLoc.ServiceType, sourceLoc.ResourceName).ForDomain(dbDomain.Name)
8✔
1377

8✔
1378
        // section: targetBehavior
8✔
1379
        var parseTarget struct {
8✔
1380
                Request struct {
8✔
1381
                        TargetService  limes.ServiceType           `json:"target_service"`
8✔
1382
                        TargetResource limesresources.ResourceName `json:"target_resource"`
8✔
1383
                        SourceAmount   uint64                      `json:"source_amount"`
8✔
1384
                        TargetAmount   uint64                      `json:"target_amount"`
8✔
1385
                } `json:"commitment"`
8✔
1386
        }
8✔
1387
        if !RequireJSON(w, r, &parseTarget) {
8✔
1388
                return
×
1389
        }
×
1390
        req := parseTarget.Request
8✔
1391
        serviceInfos, err := p.Cluster.AllServiceInfos()
8✔
1392
        if respondwith.ErrorText(w, err) {
8✔
NEW
1393
                return
×
NEW
1394
        }
×
1395
        nm := core.BuildResourceNameMapping(p.Cluster, serviceInfos)
8✔
1396
        targetServiceType, targetResourceName, exists := nm.MapFromV1API(req.TargetService, req.TargetResource)
8✔
1397
        if !exists {
8✔
1398
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", req.TargetService, req.TargetResource)
×
1399
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1400
                return
×
1401
        }
×
1402
        targetBehavior := p.Cluster.CommitmentBehaviorForResource(targetServiceType, targetResourceName).ForDomain(dbDomain.Name)
8✔
1403
        if sourceLoc.ResourceName == targetResourceName && sourceLoc.ServiceType == targetServiceType {
9✔
1404
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
1✔
1405
                return
1✔
1406
        }
1✔
1407
        if len(targetBehavior.Durations) == 0 {
7✔
1408
                msg := fmt.Sprintf("commitments are not enabled for resource %s/%s", req.TargetService, req.TargetResource)
×
1409
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1410
                return
×
1411
        }
×
1412
        rate, ok := sourceBehavior.GetConversionRateTo(targetBehavior).Unpack()
7✔
1413
        if !ok {
8✔
1414
                msg := fmt.Sprintf("commitment is not convertible into resource %s/%s", req.TargetService, req.TargetResource)
1✔
1415
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1416
                return
1✔
1417
        }
1✔
1418

1419
        // section: conversion
1420
        if req.SourceAmount > dbCommitment.Amount {
6✔
1421
                msg := fmt.Sprintf("unprocessable source amount. provided: %v, commitment: %v", req.SourceAmount, dbCommitment.Amount)
×
1422
                http.Error(w, msg, http.StatusConflict)
×
1423
                return
×
1424
        }
×
1425
        conversionAmount := (req.SourceAmount / rate.FromAmount) * rate.ToAmount
6✔
1426
        remainderAmount := req.SourceAmount % rate.FromAmount
6✔
1427
        if remainderAmount > 0 {
8✔
1428
                msg := fmt.Sprintf("amount: %v does not fit into conversion rate of: %v", req.SourceAmount, rate.FromAmount)
2✔
1429
                http.Error(w, msg, http.StatusConflict)
2✔
1430
                return
2✔
1431
        }
2✔
1432
        if conversionAmount != req.TargetAmount {
5✔
1433
                msg := fmt.Sprintf("conversion mismatch. provided: %v, calculated: %v", req.TargetAmount, conversionAmount)
1✔
1434
                http.Error(w, msg, http.StatusConflict)
1✔
1435
                return
1✔
1436
        }
1✔
1437

1438
        tx, err := p.DB.Begin()
3✔
1439
        if respondwith.ErrorText(w, err) {
3✔
1440
                return
×
1441
        }
×
1442
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1443

3✔
1444
        var (
3✔
1445
                targetResourceID   db.ProjectResourceID
3✔
1446
                targetAZResourceID db.ProjectAZResourceID
3✔
1447
        )
3✔
1448
        err = p.DB.QueryRow(findTargetAZResourceByTargetProjectQuery, dbProject.ID, targetServiceType, targetResourceName, sourceLoc.AvailabilityZone).
3✔
1449
                Scan(&targetResourceID, &targetAZResourceID)
3✔
1450
        if respondwith.ErrorText(w, err) {
3✔
1451
                return
×
1452
        }
×
1453
        // defense in depth. ServiceType and ResourceName of source and target are already checked. Here it's possible to explicitly check the ID's.
1454
        if dbCommitment.AZResourceID == targetAZResourceID {
3✔
1455
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
×
1456
                return
×
1457
        }
×
1458
        targetLoc := core.AZResourceLocation{
3✔
1459
                ServiceType:      targetServiceType,
3✔
1460
                ResourceName:     targetResourceName,
3✔
1461
                AvailabilityZone: sourceLoc.AvailabilityZone,
3✔
1462
        }
3✔
1463
        // The commitment at the source resource was already confirmed and checked.
3✔
1464
        // Therefore only the addition to the target resource has to be checked against.
3✔
1465
        if dbCommitment.ConfirmedAt.IsSome() {
5✔
1466
                ok, err := datamodel.CanConfirmNewCommitment(targetLoc, targetResourceID, conversionAmount, p.Cluster, p.DB)
2✔
1467
                if respondwith.ErrorText(w, err) {
2✔
1468
                        return
×
1469
                }
×
1470
                if !ok {
3✔
1471
                        http.Error(w, "not enough capacity to confirm the commitment", http.StatusUnprocessableEntity)
1✔
1472
                        return
1✔
1473
                }
1✔
1474
        }
1475

1476
        auditEvent := commitmentEventTarget{
2✔
1477
                DomainID:    dbDomain.UUID,
2✔
1478
                DomainName:  dbDomain.Name,
2✔
1479
                ProjectID:   dbProject.UUID,
2✔
1480
                ProjectName: dbProject.Name,
2✔
1481
        }
2✔
1482

2✔
1483
        var (
2✔
1484
                relatedCommitmentIDs   []db.ProjectCommitmentID
2✔
1485
                relatedCommitmentUUIDs []db.ProjectCommitmentUUID
2✔
1486
        )
2✔
1487
        remainingAmount := dbCommitment.Amount - req.SourceAmount
2✔
1488
        serviceInfo := core.InfoForService(serviceInfos, sourceLoc.ServiceType)
2✔
1489
        resourceInfo := core.InfoForResource(serviceInfo, sourceLoc.ResourceName)
2✔
1490
        if remainingAmount > 0 {
3✔
1491
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
1✔
1492
                if respondwith.ErrorText(w, err) {
1✔
1493
                        return
×
1494
                }
×
1495
                relatedCommitmentIDs = append(relatedCommitmentIDs, remainingCommitment.ID)
1✔
1496
                relatedCommitmentUUIDs = append(relatedCommitmentUUIDs, remainingCommitment.UUID)
1✔
1497
                err = tx.Insert(&remainingCommitment)
1✔
1498
                if respondwith.ErrorText(w, err) {
1✔
1499
                        return
×
1500
                }
×
1501
                auditEvent.Commitments = append(auditEvent.Commitments,
1✔
1502
                        p.convertCommitmentToDisplayForm(remainingCommitment, sourceLoc, token, resourceInfo.Unit),
1✔
1503
                )
1✔
1504
        }
1505

1506
        convertedCommitment, err := p.buildConvertedCommitment(dbCommitment, targetAZResourceID, conversionAmount)
2✔
1507
        if respondwith.ErrorText(w, err) {
2✔
1508
                return
×
1509
        }
×
1510
        relatedCommitmentIDs = append(relatedCommitmentIDs, convertedCommitment.ID)
2✔
1511
        relatedCommitmentUUIDs = append(relatedCommitmentUUIDs, convertedCommitment.UUID)
2✔
1512
        err = tx.Insert(&convertedCommitment)
2✔
1513
        if respondwith.ErrorText(w, err) {
2✔
1514
                return
×
1515
        }
×
1516

1517
        // supersede the original commitment
1518
        now := p.timeNow()
2✔
1519
        supersedeContext := db.CommitmentWorkflowContext{
2✔
1520
                Reason:                 db.CommitmentReasonConvert,
2✔
1521
                RelatedCommitmentIDs:   relatedCommitmentIDs,
2✔
1522
                RelatedCommitmentUUIDs: relatedCommitmentUUIDs,
2✔
1523
        }
2✔
1524
        buf, err := json.Marshal(supersedeContext)
2✔
1525
        if respondwith.ErrorText(w, err) {
2✔
1526
                return
×
1527
        }
×
1528
        dbCommitment.State = db.CommitmentStateSuperseded
2✔
1529
        dbCommitment.SupersededAt = Some(now)
2✔
1530
        dbCommitment.SupersedeContextJSON = Some(json.RawMessage(buf))
2✔
1531
        _, err = tx.Update(&dbCommitment)
2✔
1532
        if respondwith.ErrorText(w, err) {
2✔
1533
                return
×
1534
        }
×
1535

1536
        err = tx.Commit()
2✔
1537
        if respondwith.ErrorText(w, err) {
2✔
1538
                return
×
1539
        }
×
1540

1541
        c := p.convertCommitmentToDisplayForm(convertedCommitment, targetLoc, token, resourceInfo.Unit)
2✔
1542
        auditEvent.Commitments = append([]limesresources.Commitment{c}, auditEvent.Commitments...)
2✔
1543
        auditEvent.WorkflowContext = Some(db.CommitmentWorkflowContext{
2✔
1544
                Reason:                 db.CommitmentReasonSplit,
2✔
1545
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1546
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
2✔
1547
        })
2✔
1548
        p.auditor.Record(audittools.Event{
2✔
1549
                Time:       p.timeNow(),
2✔
1550
                Request:    r,
2✔
1551
                User:       token,
2✔
1552
                ReasonCode: http.StatusAccepted,
2✔
1553
                Action:     cadf.UpdateAction,
2✔
1554
                Target:     auditEvent,
2✔
1555
        })
2✔
1556

2✔
1557
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1558
}
1559

1560
// ExtendCommitmentDuration handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/update-duration
1561
func (p *v1Provider) UpdateCommitmentDuration(w http.ResponseWriter, r *http.Request) {
6✔
1562
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/update-duration")
6✔
1563
        token := p.CheckToken(r)
6✔
1564
        if !token.Require(w, "project:edit") {
6✔
1565
                return
×
1566
        }
×
1567
        commitmentID := mux.Vars(r)["commitment_id"]
6✔
1568
        if commitmentID == "" {
6✔
1569
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1570
                return
×
1571
        }
×
1572
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
1573
        if dbDomain == nil {
6✔
1574
                return
×
1575
        }
×
1576
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
1577
        if dbProject == nil {
6✔
1578
                return
×
1579
        }
×
1580
        var Request struct {
6✔
1581
                Duration limesresources.CommitmentDuration `json:"duration"`
6✔
1582
        }
6✔
1583
        req := Request
6✔
1584
        if !RequireJSON(w, r, &req) {
6✔
1585
                return
×
1586
        }
×
1587

1588
        var dbCommitment db.ProjectCommitment
6✔
1589
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
6✔
1590
        if errors.Is(err, sql.ErrNoRows) {
6✔
1591
                http.Error(w, "no such commitment", http.StatusNotFound)
×
1592
                return
×
1593
        } else if respondwith.ErrorText(w, err) {
6✔
1594
                return
×
1595
        }
×
1596

1597
        now := p.timeNow()
6✔
1598
        if dbCommitment.ExpiresAt.Before(now) || dbCommitment.ExpiresAt.Equal(now) {
7✔
1599
                http.Error(w, "unable to process expired commitment", http.StatusForbidden)
1✔
1600
                return
1✔
1601
        }
1✔
1602

1603
        if dbCommitment.State == db.CommitmentStateSuperseded {
6✔
1604
                msg := fmt.Sprintf("unable to operate on commitment with a state of %s", dbCommitment.State)
1✔
1605
                http.Error(w, msg, http.StatusForbidden)
1✔
1606
                return
1✔
1607
        }
1✔
1608

1609
        var loc core.AZResourceLocation
4✔
1610
        err = p.DB.QueryRow(findProjectAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
4✔
1611
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
4✔
1612
        if errors.Is(err, sql.ErrNoRows) {
4✔
1613
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1614
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1615
                return
×
1616
        } else if respondwith.ErrorText(w, err) {
4✔
1617
                return
×
1618
        }
×
1619
        behavior := p.Cluster.CommitmentBehaviorForResource(loc.ServiceType, loc.ResourceName).ForDomain(dbDomain.Name)
4✔
1620
        if !slices.Contains(behavior.Durations, req.Duration) {
5✔
1621
                msg := fmt.Sprintf("provided duration: %s does not match the config %v", req.Duration, behavior.Durations)
1✔
1622
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1623
                return
1✔
1624
        }
1✔
1625

1626
        newExpiresAt := req.Duration.AddTo(dbCommitment.ConfirmBy.UnwrapOr(dbCommitment.CreatedAt))
3✔
1627
        if newExpiresAt.Before(dbCommitment.ExpiresAt) {
4✔
1628
                msg := fmt.Sprintf("duration change from %s to %s forbidden", dbCommitment.Duration, req.Duration)
1✔
1629
                http.Error(w, msg, http.StatusForbidden)
1✔
1630
                return
1✔
1631
        }
1✔
1632

1633
        dbCommitment.Duration = req.Duration
2✔
1634
        dbCommitment.ExpiresAt = newExpiresAt
2✔
1635
        _, err = p.DB.Update(&dbCommitment)
2✔
1636
        if respondwith.ErrorText(w, err) {
2✔
1637
                return
×
1638
        }
×
1639

1640
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
2✔
1641
        if respondwith.ErrorText(w, err) {
2✔
NEW
1642
                return
×
NEW
1643
        }
×
1644
        serviceInfo, ok := maybeServiceInfo.Unpack()
2✔
1645
        if !ok {
2✔
NEW
1646
                http.Error(w, "service not found", http.StatusNotFound)
×
NEW
1647
                return
×
NEW
1648
        }
×
1649
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
2✔
1650
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
2✔
1651
        p.auditor.Record(audittools.Event{
2✔
1652
                Time:       p.timeNow(),
2✔
1653
                Request:    r,
2✔
1654
                User:       token,
2✔
1655
                ReasonCode: http.StatusOK,
2✔
1656
                Action:     cadf.UpdateAction,
2✔
1657
                Target: commitmentEventTarget{
2✔
1658
                        DomainID:    dbDomain.UUID,
2✔
1659
                        DomainName:  dbDomain.Name,
2✔
1660
                        ProjectID:   dbProject.UUID,
2✔
1661
                        ProjectName: dbProject.Name,
2✔
1662
                        Commitments: []limesresources.Commitment{c},
2✔
1663
                },
2✔
1664
        })
2✔
1665

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