2022-07-20 11:50:49 +02:00
package main
import (
2022-07-20 18:10:52 +02:00
"context"
2022-07-20 11:50:49 +02:00
"database/sql"
"errors"
"fmt"
2022-07-20 18:10:52 +02:00
"regexp"
2022-07-20 11:50:49 +02:00
"strings"
2022-07-20 18:10:52 +02:00
"time"
"github.com/zitadel/logging"
2022-07-20 11:50:49 +02:00
)
2022-07-20 18:10:52 +02:00
var idRegexp = regexp . MustCompile ( "[0-9]{16}" )
func ids ( ctx context . Context , cfg * E2EConfig , dbClient * sql . DB ) ( string , string , error ) {
2022-07-20 11:50:49 +02:00
zitadelProjectResourceID := strings . TrimPrefix ( cfg . ZitadelProjectResourceID , "bignumber-" )
instanceID := strings . TrimPrefix ( cfg . InstanceID , "bignumber-" )
2022-07-20 18:10:52 +02:00
if idRegexp . MatchString ( zitadelProjectResourceID ) && idRegexp . MatchString ( instanceID ) {
2022-07-20 11:50:49 +02:00
return zitadelProjectResourceID , instanceID , nil
}
2022-07-20 18:10:52 +02:00
projCtx , projCancel := context . WithTimeout ( ctx , time . Minute )
defer projCancel ( )
zitadelProjectResourceID , err := querySingleString ( projCtx , dbClient , ` select aggregate_id from eventstore.events where event_type = 'project.added' and event_data = ' { "name": "ZITADEL"}' ` )
2022-07-20 11:50:49 +02:00
if err != nil {
return "" , "" , err
}
2022-07-20 18:10:52 +02:00
instCtx , instCancel := context . WithTimeout ( ctx , time . Minute )
defer instCancel ( )
instanceID , err = querySingleString ( instCtx , dbClient , ` select aggregate_id from eventstore.events where event_type = 'instance.added' and event_data = ' { "name": "Localhost"}' ` )
2022-07-20 11:50:49 +02:00
return instanceID , zitadelProjectResourceID , err
}
2022-07-20 18:10:52 +02:00
func querySingleString ( ctx context . Context , dbClient * sql . DB , query string ) ( _ string , err error ) {
2022-07-20 11:50:49 +02:00
defer func ( ) {
if err != nil {
err = fmt . Errorf ( "getting single string failed for query %s: %w" , query , err )
}
} ( )
rows , err := dbClient . Query ( query )
if err != nil {
return "" , err
}
var read bool
id := new ( string )
for rows . Next ( ) {
if read {
return "" , errors . New ( "read more than one row" )
}
read = true
if err := rows . Scan ( id ) ; err != nil {
return "" , err
}
}
2022-07-20 18:10:52 +02:00
2022-07-20 11:50:49 +02:00
if ! read {
2022-07-20 18:10:52 +02:00
select {
case <- ctx . Done ( ) :
return "" , ctx . Err ( )
default :
logging . Warningf ( "no results for query yet. retrying in a second. query: %s" , query )
time . Sleep ( time . Second )
return querySingleString ( ctx , dbClient , query )
}
2022-07-20 11:50:49 +02:00
}
if * id == "" {
return "" , errors . New ( "could not parse result" )
}
2022-07-20 18:10:52 +02:00
2022-07-20 11:50:49 +02:00
return * id , nil
}