79 lines
2.3 KiB
Go
79 lines
2.3 KiB
Go
package model
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"modelRT/common"
|
|
"modelRT/constants"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// DataObjectRedisAliasKey returns the Redis string key used to resolve any
|
|
// supported token form to the one canonical full-token hash.
|
|
func DataObjectRedisAliasKey(dataObjectType constants.DataObjectType, token string) (string, error) {
|
|
switch dataObjectType {
|
|
case constants.DataObjectTypeParameter:
|
|
return constants.RedisParameterDataObjectAliasPrefix + token, nil
|
|
case constants.DataObjectTypeMeasurement:
|
|
return constants.RedisMeasurementDataObjectAliasPrefix + token, nil
|
|
default:
|
|
return "", fmt.Errorf("unsupported data object type %q", dataObjectType)
|
|
}
|
|
}
|
|
|
|
// ResolveDataObjectRedisKey resolves a full or short token to the canonical
|
|
// full-token Redis hash created during data-object initialization.
|
|
func ResolveDataObjectRedisKey(
|
|
ctx context.Context,
|
|
rdb *redis.Client,
|
|
dataObjectType constants.DataObjectType,
|
|
token string,
|
|
) (string, error) {
|
|
if rdb == nil {
|
|
return "", fmt.Errorf("redis client is not initialized")
|
|
}
|
|
classifiedType, err := ClassifyDataObjectToken(token)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if classifiedType != dataObjectType {
|
|
return "", fmt.Errorf("token %q is %q, expected %q", token, classifiedType, dataObjectType)
|
|
}
|
|
|
|
aliasKey, err := DataObjectRedisAliasKey(dataObjectType, token)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
canonicalKey, err := rdb.Get(ctx, aliasKey).Result()
|
|
if errors.Is(err, redis.Nil) {
|
|
switch dataObjectType {
|
|
case constants.DataObjectTypeParameter:
|
|
return "", fmt.Errorf("%w: %q", common.ErrParameterTokenNotFound, token)
|
|
case constants.DataObjectTypeMeasurement:
|
|
return "", fmt.Errorf("%w: %q", common.ErrMeasurementTokenNotFound, token)
|
|
}
|
|
}
|
|
if err != nil {
|
|
return "", fmt.Errorf("resolve redis data-object alias %q: %w", token, err)
|
|
}
|
|
if canonicalKey == "" {
|
|
return "", fmt.Errorf("redis data-object alias %q points to an empty key", token)
|
|
}
|
|
keyType, err := rdb.Type(ctx, canonicalKey).Result()
|
|
if err != nil {
|
|
return "", fmt.Errorf("query canonical redis key type for %q: %w", token, err)
|
|
}
|
|
if keyType != "hash" {
|
|
return "", fmt.Errorf(
|
|
"redis data-object alias %q points to key %q with type %q, expected hash",
|
|
token,
|
|
canonicalKey,
|
|
keyType,
|
|
)
|
|
}
|
|
return canonicalKey, nil
|
|
}
|