add: helper services added
This commit is contained in:
parent
690fe2f603
commit
25f18e2c1b
@ -0,0 +1,423 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cipher
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - Cipher
|
||||
|
|
||||
| Purpose:
|
||||
| - Provide reusable AES-256 encryption and decryption capabilities
|
||||
| supporting standard and salted file formats through a unified
|
||||
| interface.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Support only AES-256 operations.
|
||||
| - Preserve input immutability.
|
||||
| - Never expose sensitive values in error responses.
|
||||
| - Fail safely without producing partial output.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimCipher("encrypt-standard", config)
|
||||
| - ObrimCipher("decrypt-salted", config)
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
| - Scionite
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package cipher
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"go/module/name/essential/external/service/helper/log"
|
||||
"go/module/name/essential/external/service/helper/status"
|
||||
)
|
||||
|
||||
const (
|
||||
obrimCipherAlgorithm = "AES-256"
|
||||
obrimCipherSignature = "OBRIMCIPHER"
|
||||
obrimCipherVersion = "1"
|
||||
obrimCipherSaltSize = 32
|
||||
)
|
||||
|
||||
type obrimCipherResponse struct {
|
||||
Status bool `json:"status"`
|
||||
Code string `json:"code"`
|
||||
Payload any `json:"payload"`
|
||||
}
|
||||
|
||||
// Function Name: ObrimCipher
|
||||
// Function Purpose: Execute encryption or decryption workflows.
|
||||
func ObrimCipher(operationType string, config map[string]any) map[string]any {
|
||||
log.ObrimLog("INIT", "Cipher utility started.")
|
||||
|
||||
if errCode := obrimCipherValidateType(operationType); errCode != "" {
|
||||
return obrimCipherBuildResponse(false, errCode, nil)
|
||||
}
|
||||
|
||||
if errCode := obrimCipherValidateConfig(config); errCode != "" {
|
||||
return obrimCipherBuildResponse(false, errCode, nil)
|
||||
}
|
||||
|
||||
keyValue := config["key"].(string)
|
||||
|
||||
if errCode := obrimCipherValidateKey(keyValue); errCode != "" {
|
||||
return obrimCipherBuildResponse(false, errCode, nil)
|
||||
}
|
||||
|
||||
inputPath, err := obrimCipherResolvePath(config["input"].(string))
|
||||
if err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_INPUT_PATH_VALIDATION", nil)
|
||||
}
|
||||
|
||||
outputPath, err := obrimCipherResolvePath(config["output"].(string))
|
||||
if err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_OUTPUT_PATH_VALIDATION", nil)
|
||||
}
|
||||
|
||||
inputData, err := obrimCipherReadInput(inputPath)
|
||||
if err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_SOURCE_FILE_ACCESS", nil)
|
||||
}
|
||||
|
||||
switch operationType {
|
||||
case "encrypt-standard":
|
||||
outputData, err := obrimCipherEncryptStandard(inputData, []byte(keyValue))
|
||||
if err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_ENCRYPTION", nil)
|
||||
}
|
||||
|
||||
if err := obrimCipherWriteOutput(outputPath, outputData); err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_OUTPUT_WRITE", nil)
|
||||
}
|
||||
|
||||
status.ObrimStatus("SUCCESS", "Encryption completed.")
|
||||
|
||||
return obrimCipherBuildResponse(true, "SUCCESS_ENCRYPT_STANDARD", map[string]any{
|
||||
"operation": operationType,
|
||||
"algorithm": obrimCipherAlgorithm,
|
||||
"inputPath": inputPath,
|
||||
"outputPath": outputPath,
|
||||
})
|
||||
|
||||
case "encrypt-salted":
|
||||
outputData, err := obrimCipherEncryptSalted(inputData, []byte(keyValue))
|
||||
if err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_ENCRYPTION", nil)
|
||||
}
|
||||
|
||||
if err := obrimCipherWriteOutput(outputPath, outputData); err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_OUTPUT_WRITE", nil)
|
||||
}
|
||||
|
||||
return obrimCipherBuildResponse(true, "SUCCESS_ENCRYPT_SALTED", map[string]any{
|
||||
"operation": operationType,
|
||||
"algorithm": obrimCipherAlgorithm,
|
||||
"format": obrimCipherSignature,
|
||||
"version": obrimCipherVersion,
|
||||
"inputPath": inputPath,
|
||||
"outputPath": outputPath,
|
||||
})
|
||||
|
||||
case "decrypt-standard":
|
||||
outputData, err := obrimCipherDecryptStandard(inputData, []byte(keyValue))
|
||||
if err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_DECRYPTION", nil)
|
||||
}
|
||||
|
||||
if err := obrimCipherWriteOutput(outputPath, outputData); err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_OUTPUT_WRITE", nil)
|
||||
}
|
||||
|
||||
return obrimCipherBuildResponse(true, "SUCCESS_DECRYPT_STANDARD", map[string]any{
|
||||
"operation": operationType,
|
||||
"algorithm": obrimCipherAlgorithm,
|
||||
"inputPath": inputPath,
|
||||
"outputPath": outputPath,
|
||||
})
|
||||
|
||||
case "decrypt-salted":
|
||||
signature, version, err := obrimCipherParseHeader(inputData)
|
||||
if err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_SIGNATURE_VALIDATION", nil)
|
||||
}
|
||||
|
||||
outputData, err := obrimCipherDecryptSalted(inputData, []byte(keyValue))
|
||||
if err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_DECRYPTION", nil)
|
||||
}
|
||||
|
||||
if err := obrimCipherWriteOutput(outputPath, outputData); err != nil {
|
||||
return obrimCipherBuildResponse(false, "FAILED_OUTPUT_WRITE", nil)
|
||||
}
|
||||
|
||||
return obrimCipherBuildResponse(true, "SUCCESS_DECRYPT_SALTED", map[string]any{
|
||||
"operation": operationType,
|
||||
"algorithm": obrimCipherAlgorithm,
|
||||
"format": signature,
|
||||
"version": version,
|
||||
"inputPath": inputPath,
|
||||
"outputPath": outputPath,
|
||||
})
|
||||
}
|
||||
|
||||
return obrimCipherBuildResponse(false, "FAILED_OPERATION", nil)
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherValidateType
|
||||
// Function Purpose: Validate operation type selection.
|
||||
func obrimCipherValidateType(operationType string) string {
|
||||
switch operationType {
|
||||
case "encrypt-standard", "encrypt-salted", "decrypt-standard", "decrypt-salted":
|
||||
return ""
|
||||
default:
|
||||
return "FAILED_TYPE_VALIDATION"
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherValidateConfig
|
||||
// Function Purpose: Validate configuration values.
|
||||
func obrimCipherValidateConfig(config map[string]any) string {
|
||||
if config == nil {
|
||||
return "FAILED_CONFIG_VALIDATION"
|
||||
}
|
||||
|
||||
_, keyOK := config["key"].(string)
|
||||
_, inputOK := config["input"].(string)
|
||||
_, outputOK := config["output"].(string)
|
||||
|
||||
if !keyOK || !inputOK || !outputOK {
|
||||
return "FAILED_CONFIG_VALIDATION"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherValidateKey
|
||||
// Function Purpose: Validate AES-256 compatible key requirements.
|
||||
func obrimCipherValidateKey(key string) string {
|
||||
if len([]byte(key)) != 32 {
|
||||
return "FAILED_KEY_VALIDATION"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherResolvePath
|
||||
// Function Purpose: Resolve relative paths into absolute paths.
|
||||
func obrimCipherResolvePath(path string) (string, error) {
|
||||
return filepath.Abs(path)
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherReadInput
|
||||
// Function Purpose: Read source file content.
|
||||
func obrimCipherReadInput(path string) ([]byte, error) {
|
||||
return os.ReadFile(path)
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherWriteOutput
|
||||
// Function Purpose: Write processed output to destination file.
|
||||
func obrimCipherWriteOutput(path string, data []byte) error {
|
||||
tempPath := path + ".tmp"
|
||||
|
||||
if err := os.WriteFile(tempPath, data, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.Rename(tempPath, path)
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherBuildResponse
|
||||
// Function Purpose: Build standardized utility responses.
|
||||
func obrimCipherBuildResponse(statusValue bool, code string, payload any) map[string]any {
|
||||
response := obrimCipherResponse{
|
||||
Status: statusValue,
|
||||
Code: code,
|
||||
Payload: payload,
|
||||
}
|
||||
|
||||
buffer, _ := json.Marshal(response)
|
||||
|
||||
var result map[string]any
|
||||
_ = json.Unmarshal(buffer, &result)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherEncryptStandard
|
||||
// Function Purpose: Encrypt data using AES-256 without salt metadata.
|
||||
func obrimCipherEncryptStandard(data []byte, key []byte) ([]byte, error) {
|
||||
return obrimCipherEncrypt(data, key)
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherGenerateSalt
|
||||
// Function Purpose: Generate a cryptographically secure random salt.
|
||||
func obrimCipherGenerateSalt() ([]byte, error) {
|
||||
salt := make([]byte, obrimCipherSaltSize)
|
||||
_, err := io.ReadFull(rand.Reader, salt)
|
||||
return salt, err
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherBuildHeader
|
||||
// Function Purpose: Build encrypted file signature and version header.
|
||||
func obrimCipherBuildHeader() []byte {
|
||||
return []byte(obrimCipherSignature + ":" + obrimCipherVersion + ":")
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherEncryptSalted
|
||||
// Function Purpose: Encrypt data using AES-256 with embedded salt metadata.
|
||||
func obrimCipherEncryptSalted(data []byte, key []byte) ([]byte, error) {
|
||||
salt, err := obrimCipherGenerateSalt()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
derivedKey := sha256.Sum256(append(key, salt...))
|
||||
|
||||
ciphertext, err := obrimCipherEncrypt(data, derivedKey[:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
output := bytes.Buffer{}
|
||||
output.Write(obrimCipherBuildHeader())
|
||||
output.Write(salt)
|
||||
output.Write(ciphertext)
|
||||
|
||||
return output.Bytes(), nil
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherDecryptStandard
|
||||
// Function Purpose: Decrypt AES-256 encrypted data without salt metadata.
|
||||
func obrimCipherDecryptStandard(data []byte, key []byte) ([]byte, error) {
|
||||
return obrimCipherDecrypt(data, key)
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherParseHeader
|
||||
// Function Purpose: Parse encrypted file signature and version metadata.
|
||||
func obrimCipherParseHeader(data []byte) (string, string, error) {
|
||||
header := obrimCipherBuildHeader()
|
||||
|
||||
if len(data) < len(header) {
|
||||
return "", "", os.ErrInvalid
|
||||
}
|
||||
|
||||
if !bytes.Equal(data[:len(header)], header) {
|
||||
return "", "", os.ErrInvalid
|
||||
}
|
||||
|
||||
return obrimCipherSignature, obrimCipherVersion, nil
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherExtractSalt
|
||||
// Function Purpose: Extract embedded salt from encrypted data.
|
||||
func obrimCipherExtractSalt(data []byte) ([]byte, error) {
|
||||
headerLength := len(obrimCipherBuildHeader())
|
||||
|
||||
if len(data) < headerLength+obrimCipherSaltSize {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
|
||||
return data[headerLength : headerLength+obrimCipherSaltSize], nil
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherExtractPayload
|
||||
// Function Purpose: Extract encrypted payload from the encrypted file.
|
||||
func obrimCipherExtractPayload(data []byte) ([]byte, error) {
|
||||
headerLength := len(obrimCipherBuildHeader())
|
||||
offset := headerLength + obrimCipherSaltSize
|
||||
|
||||
if len(data) <= offset {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
|
||||
return data[offset:], nil
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherDecryptSalted
|
||||
// Function Purpose: Decrypt AES-256 encrypted data using extracted salt metadata.
|
||||
func obrimCipherDecryptSalted(data []byte, key []byte) ([]byte, error) {
|
||||
salt, err := obrimCipherExtractSalt(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
payload, err := obrimCipherExtractPayload(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
derivedKey := sha256.Sum256(append(key, salt...))
|
||||
|
||||
return obrimCipherDecrypt(payload, derivedKey[:])
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherEncrypt
|
||||
// Function Purpose: Perform AES-256 GCM encryption.
|
||||
func obrimCipherEncrypt(data []byte, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Logic:
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ciphertext := gcm.Seal(nil, nonce, data, nil)
|
||||
|
||||
return append(nonce, ciphertext...), nil
|
||||
}
|
||||
|
||||
// Function Name: obrimCipherDecrypt
|
||||
// Function Purpose: Perform AES-256 GCM decryption.
|
||||
func obrimCipherDecrypt(data []byte, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
nonceSize := gcm.NonceSize()
|
||||
|
||||
if len(data) < nonceSize {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
|
||||
nonce := data[:nonceSize]
|
||||
ciphertext := data[nonceSize:]
|
||||
|
||||
return gcm.Open(nil, nonce, ciphertext, nil)
|
||||
}
|
||||
@ -0,0 +1,497 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Codec
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - Codec
|
||||
|
|
||||
| Purpose:
|
||||
| - Provide unified encoding and decoding capabilities using Base8,
|
||||
| Base10, Base16, Base32, Base64, and Sqids with centralized
|
||||
| validation, dispatching, transformation handling, and structured
|
||||
| result processing.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Validate all required parameters before execution.
|
||||
| - Reject unsupported operations and formats.
|
||||
| - Return standardized structured responses.
|
||||
| - Prevent application crashes through safe error handling.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimCodec("encode", config)
|
||||
| - ObrimCodec("decode", config)
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package codec
|
||||
|
||||
import (
|
||||
"encoding/base32"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/sqids/sqids-go"
|
||||
)
|
||||
|
||||
// Function Purpose: Standardized utility response structure.
|
||||
type ObrimCodecResponse struct {
|
||||
Status bool `json:"status"`
|
||||
Code string `json:"code"`
|
||||
Payload map[string]any `json:"payload"`
|
||||
}
|
||||
|
||||
// Function Purpose: Validate configuration, dispatch codec operations, and return structured results.
|
||||
func ObrimCodec(operation string, config map[string]any) (result ObrimCodecResponse) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
result = ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_PANIC",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if validation := obrimCodecValidation(operation, config); validation != nil {
|
||||
return *validation
|
||||
}
|
||||
|
||||
return obrimCodecDispatch(operation, config)
|
||||
}
|
||||
|
||||
// Function Purpose: Validate required parameters, supported operations, formats, and parameter types.
|
||||
func obrimCodecValidation(operation string, config map[string]any) *ObrimCodecResponse {
|
||||
if operation != "encode" && operation != "decode" {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_UNSUPPORTED_OPERATION",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
// Logic: Validate format.
|
||||
formatValue, exists := config["format"]
|
||||
if !exists {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_MISSING_FORMAT",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
format, ok := formatValue.(string)
|
||||
if !ok {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_INVALID_FORMAT_TYPE",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
switch format {
|
||||
case "base8", "base10", "base16", "base32", "base64", "sqids":
|
||||
default:
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_UNSUPPORTED_FORMAT",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
// Logic: Validate data.
|
||||
dataValue, exists := config["data"]
|
||||
if !exists {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_MISSING_DATA",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
switch dataValue.(type) {
|
||||
case string, []byte:
|
||||
default:
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_INVALID_DATA_TYPE",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
// Logic: Validate charset.
|
||||
charsetValue, exists := config["charset"]
|
||||
if !exists {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_MISSING_CHARSET",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := charsetValue.(string); !ok {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_INVALID_CHARSET_TYPE",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
// Logic: Validate salt.
|
||||
saltValue, exists := config["salt"]
|
||||
if !exists {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_MISSING_SALT",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := saltValue.(string); !ok {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_INVALID_SALT_TYPE",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
if format == "sqids" {
|
||||
lengthValue, exists := config["length"]
|
||||
if !exists {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_MISSING_LENGTH",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
switch lengthValue.(type) {
|
||||
case int, int8, int16, int32, int64:
|
||||
default:
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_INVALID_LENGTH_TYPE",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
caseValue, exists := config["case"]
|
||||
if !exists {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_MISSING_CASE",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
caseRule, ok := caseValue.(string)
|
||||
if !ok {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_INVALID_CASE_TYPE",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
if caseRule != "lower" && caseRule != "upper" {
|
||||
return &ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_INVALID_CASE_VALUE",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Function Purpose: Route validated requests to the appropriate codec implementation.
|
||||
func obrimCodecDispatch(operation string, config map[string]any) ObrimCodecResponse {
|
||||
format := config["format"].(string)
|
||||
|
||||
var (
|
||||
// Logic:
|
||||
value string
|
||||
err error
|
||||
)
|
||||
|
||||
switch operation {
|
||||
case "encode":
|
||||
switch format {
|
||||
case "base8":
|
||||
value, err = obrimCodecEncodeBase8(config)
|
||||
case "base10":
|
||||
value, err = obrimCodecEncodeBase10(config)
|
||||
case "base16":
|
||||
value, err = obrimCodecEncodeBase16(config)
|
||||
case "base32":
|
||||
value, err = obrimCodecEncodeBase32(config)
|
||||
case "base64":
|
||||
value, err = obrimCodecEncodeBase64(config)
|
||||
case "sqids":
|
||||
value, err = obrimCodecEncodeSqids(config)
|
||||
}
|
||||
|
||||
case "decode":
|
||||
switch format {
|
||||
case "base8":
|
||||
value, err = obrimCodecDecodeBase8(config)
|
||||
case "base10":
|
||||
value, err = obrimCodecDecodeBase10(config)
|
||||
case "base16":
|
||||
value, err = obrimCodecDecodeBase16(config)
|
||||
case "base32":
|
||||
value, err = obrimCodecDecodeBase32(config)
|
||||
case "base64":
|
||||
value, err = obrimCodecDecodeBase64(config)
|
||||
case "sqids":
|
||||
value, err = obrimCodecDecodeSqids(config)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return ObrimCodecResponse{
|
||||
Status: false,
|
||||
Code: "FAILED_OPERATION",
|
||||
Payload: nil,
|
||||
}
|
||||
}
|
||||
|
||||
return ObrimCodecResponse{
|
||||
Status: true,
|
||||
Code: "SUCCESS_OPERATION",
|
||||
Payload: map[string]any{
|
||||
"operation": operation,
|
||||
"format": format,
|
||||
"value": value,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Function Purpose: Encode data using Base8 encoding.
|
||||
func obrimCodecEncodeBase8(config map[string]any) (string, error) {
|
||||
return obrimCodecEncodeRadix(config, 8)
|
||||
}
|
||||
|
||||
// Function Purpose: Encode data using Base10 encoding.
|
||||
func obrimCodecEncodeBase10(config map[string]any) (string, error) {
|
||||
return obrimCodecEncodeRadix(config, 10)
|
||||
}
|
||||
|
||||
// Function Purpose: Encode data using Base16 encoding.
|
||||
func obrimCodecEncodeBase16(config map[string]any) (string, error) {
|
||||
value := hex.EncodeToString(obrimCodecBytes(config["data"]))
|
||||
return obrimCodecApplyCase(obrimCodecTransformEncode(value, config)), nil
|
||||
}
|
||||
|
||||
// Function Purpose: Encode data using Base32 encoding.
|
||||
func obrimCodecEncodeBase32(config map[string]any) (string, error) {
|
||||
value := base32.StdEncoding.EncodeToString(obrimCodecBytes(config["data"]))
|
||||
return obrimCodecApplyCase(obrimCodecTransformEncode(value, config)), nil
|
||||
}
|
||||
|
||||
// Function Purpose: Encode data using Base64 encoding.
|
||||
func obrimCodecEncodeBase64(config map[string]any) (string, error) {
|
||||
value := base64.StdEncoding.EncodeToString(obrimCodecBytes(config["data"]))
|
||||
return obrimCodecApplyCase(obrimCodecTransformEncode(value, config)), nil
|
||||
}
|
||||
|
||||
// Function Purpose: Encode data using Sqids encoding with minimum length enforcement.
|
||||
func obrimCodecEncodeSqids(config map[string]any) (string, error) {
|
||||
length := obrimCodecLength(config["length"])
|
||||
|
||||
s, err := sqids.New(sqids.Options{
|
||||
MinLength: uint8(length),
|
||||
Alphabet: config["charset"].(string),
|
||||
Blocklist: []string{},
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
number := obrimCodecBigInt(obrimCodecBytes(config["data"])).Uint64()
|
||||
|
||||
value, err := s.Encode([]uint64{number})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return obrimCodecTransformEncode(value, config), nil
|
||||
}
|
||||
|
||||
// Function Purpose: Decode Base8 encoded data.
|
||||
func obrimCodecDecodeBase8(config map[string]any) (string, error) {
|
||||
return obrimCodecDecodeRadix(config, 8)
|
||||
}
|
||||
|
||||
// Function Purpose: Decode Base10 encoded data.
|
||||
func obrimCodecDecodeBase10(config map[string]any) (string, error) {
|
||||
return obrimCodecDecodeRadix(config, 10)
|
||||
}
|
||||
|
||||
// Function Purpose: Decode Base16 encoded data.
|
||||
func obrimCodecDecodeBase16(config map[string]any) (string, error) {
|
||||
value := obrimCodecTransformDecode(config["data"].(string), config)
|
||||
|
||||
decoded, err := hex.DecodeString(value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(decoded), nil
|
||||
}
|
||||
|
||||
// Function Purpose: Decode Base32 encoded data.
|
||||
func obrimCodecDecodeBase32(config map[string]any) (string, error) {
|
||||
value := obrimCodecTransformDecode(config["data"].(string), config)
|
||||
|
||||
decoded, err := base32.StdEncoding.DecodeString(strings.ToUpper(value))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(decoded), nil
|
||||
}
|
||||
|
||||
// Function Purpose: Decode Base64 encoded data.
|
||||
func obrimCodecDecodeBase64(config map[string]any) (string, error) {
|
||||
value := obrimCodecTransformDecode(config["data"].(string), config)
|
||||
|
||||
decoded, err := base64.StdEncoding.DecodeString(value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(decoded), nil
|
||||
}
|
||||
|
||||
// Function Purpose: Decode Sqids encoded data using deterministic length validation.
|
||||
func obrimCodecDecodeSqids(config map[string]any) (string, error) {
|
||||
length := obrimCodecLength(config["length"])
|
||||
|
||||
s, err := sqids.New(sqids.Options{
|
||||
MinLength: uint8(length),
|
||||
Alphabet: config["charset"].(string),
|
||||
Blocklist: []string{},
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
value := obrimCodecTransformDecode(config["data"].(string), config)
|
||||
|
||||
numbers := s.Decode(value)
|
||||
if len(numbers) == 0 {
|
||||
return "", fmt.Errorf("decode failed")
|
||||
}
|
||||
|
||||
return strconv.FormatUint(numbers[0], 10), nil
|
||||
}
|
||||
|
||||
// Function Purpose: Encode generic radix values.
|
||||
func obrimCodecEncodeRadix(config map[string]any, base int) (string, error) {
|
||||
value := obrimCodecBigInt(obrimCodecBytes(config["data"])).Text(base)
|
||||
value = obrimCodecTransformEncode(value, config)
|
||||
value = obrimCodecApplyCase(value, config["case"].(string))
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// Function Purpose: Decode generic radix values.
|
||||
func obrimCodecDecodeRadix(config map[string]any, base int) (string, error) {
|
||||
value := obrimCodecTransformDecode(config["data"].(string), config)
|
||||
|
||||
number := new(big.Int)
|
||||
|
||||
_, ok := number.SetString(value, base)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("invalid value")
|
||||
}
|
||||
|
||||
return string(number.Bytes()), nil
|
||||
}
|
||||
|
||||
// Function Purpose: Convert supported data into bytes.
|
||||
func obrimCodecBytes(data any) []byte {
|
||||
switch value := data.(type) {
|
||||
case string:
|
||||
return []byte(value)
|
||||
case []byte:
|
||||
return value
|
||||
default:
|
||||
return []byte{}
|
||||
}
|
||||
}
|
||||
|
||||
// Function Purpose: Convert bytes into big integer.
|
||||
func obrimCodecBigInt(data []byte) *big.Int {
|
||||
return new(big.Int).SetBytes(data)
|
||||
}
|
||||
|
||||
// Function Purpose: Apply encoding transformations.
|
||||
func obrimCodecTransformEncode(value string, config map[string]any) string {
|
||||
charset := config["charset"].(string)
|
||||
salt := config["salt"].(string)
|
||||
|
||||
return salt + charset + value
|
||||
}
|
||||
|
||||
// Function Purpose: Reverse encoding transformations.
|
||||
func obrimCodecTransformDecode(value string, config map[string]any) string {
|
||||
salt := config["salt"].(string)
|
||||
charset := config["charset"].(string)
|
||||
|
||||
value = strings.TrimPrefix(value, salt)
|
||||
value = strings.TrimPrefix(value, charset)
|
||||
|
||||
if caseRule, ok := config["case"].(string); ok {
|
||||
if caseRule == "upper" {
|
||||
value = strings.ToLower(value)
|
||||
}
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
// Function Purpose: Apply output casing rules.
|
||||
func obrimCodecApplyCase(value string, rule string) string {
|
||||
switch rule {
|
||||
case "upper":
|
||||
return strings.ToUpper(value)
|
||||
default:
|
||||
return strings.ToLower(value)
|
||||
}
|
||||
}
|
||||
|
||||
// Function Purpose: Convert supported length types into integer.
|
||||
func obrimCodecLength(value any) int {
|
||||
switch v := value.(type) {
|
||||
case int:
|
||||
return v
|
||||
case int8:
|
||||
return int(v)
|
||||
case int16:
|
||||
return int(v)
|
||||
case int32:
|
||||
return int(v)
|
||||
case int64:
|
||||
return int(v)
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,232 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Datetime
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - datetime
|
||||
|
|
||||
| Purpose:
|
||||
| - Retrieve and format the current date and time from either the
|
||||
| host system clock or a trusted NTP source using framework-
|
||||
| supported format patterns.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Validate all inputs before execution.
|
||||
| - Use framework-defined format mappings only.
|
||||
| - Return standardized response structures.
|
||||
| - Emit status and log messages for initialization, success,
|
||||
| and failure events.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimDatetime("local", map[string]any{"format":"yyyy-MM-dd"})
|
||||
| - ObrimDatetime("trusted", map[string]any{"format":"timestampsec"})
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
| - Scionite
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package datetime
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"go/module/name/essential/external/service/helper/log"
|
||||
"go/module/name/essential/external/service/helper/retriever"
|
||||
"go/module/name/essential/external/service/helper/status"
|
||||
|
||||
"github.com/beevik/ntp"
|
||||
)
|
||||
|
||||
// Mutable Variable Purpose: Framework-supported datetime pattern mappings.
|
||||
var obrimDatetimePatternMap = map[string]string{
|
||||
"yyyy-MM-dd": "2006-01-02",
|
||||
"MMM dd, yyyy": "Jan 02, 2006",
|
||||
"MMMM dd, yyyy": "January 02, 2006",
|
||||
"EEE, MMM dd, yyyy": "Mon, Jan 02, 2006",
|
||||
"EEE, MMMM dd, yyyy": "Mon, January 02, 2006",
|
||||
"EEEE, MMM dd, yyyy": "Monday, Jan 02, 2006",
|
||||
"EEEE, MMMM dd, yyyy": "Monday, January 02, 2006",
|
||||
"HH:mm:ss": "15:04:05",
|
||||
"hh:mm:ss a": "03:04:05 PM",
|
||||
"yyyy-MM-dd HH:mm:ss": "2006-01-02 15:04:05",
|
||||
"yyyy-MM-dd HH:mm:ss z": "2006-01-02 15:04:05 MST",
|
||||
"yyyy-MM-dd'T'HH:mm:ssXXX": "2006-01-02T15:04:05Z07:00",
|
||||
}
|
||||
|
||||
// Function Name: ObrimDatetime
|
||||
// Function Purpose: Retrieve and format the current date and time from a selected source using a supported format pattern.
|
||||
func ObrimDatetime(datetimeType string, config map[string]any) map[string]any {
|
||||
status.ObrimStatus("INFO", "Datetime utility initialization started.")
|
||||
log.ObrimLog("INIT", "Datetime utility initialization started.")
|
||||
|
||||
if err := obrimDatetimeValidate(datetimeType, config); err != nil {
|
||||
status.ObrimStatus("ERROR", err.Error())
|
||||
log.ObrimLog("ERROR", err.Error())
|
||||
|
||||
switch err.Error() {
|
||||
case "INVALID_TYPE":
|
||||
return obrimDatetimeResponse(false, "FAILED_INVALID_TYPE", nil)
|
||||
case "INVALID_FORMAT":
|
||||
return obrimDatetimeResponse(false, "FAILED_INVALID_FORMAT", nil)
|
||||
default:
|
||||
return obrimDatetimeResponse(false, "FAILED_VALIDATION", nil)
|
||||
}
|
||||
}
|
||||
|
||||
var currentTime time.Time
|
||||
var err error
|
||||
|
||||
switch datetimeType {
|
||||
case "local":
|
||||
currentTime, err = obrimDatetimeLocal()
|
||||
case "trusted":
|
||||
currentTime, err = obrimDatetimeTrusted()
|
||||
default:
|
||||
err = errors.New("INVALID_TYPE")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
status.ObrimStatus("ERROR", err.Error())
|
||||
log.ObrimLog("ERROR", err.Error())
|
||||
|
||||
return obrimDatetimeResponse(false, "FAILED_DATETIME_RETRIEVAL", nil)
|
||||
}
|
||||
|
||||
value, err := obrimDatetimeFormatApply(currentTime, fmt.Sprintf("%v", config["format"]))
|
||||
if err != nil {
|
||||
status.ObrimStatus("ERROR", err.Error())
|
||||
log.ObrimLog("ERROR", err.Error())
|
||||
|
||||
return obrimDatetimeResponse(false, "FAILED_INVALID_FORMAT", nil)
|
||||
}
|
||||
|
||||
status.ObrimStatus("SUCCESS", "Datetime retrieved successfully.")
|
||||
log.ObrimLog("SUCCESS", "Datetime retrieved successfully.")
|
||||
|
||||
return obrimDatetimeResponse(
|
||||
true,
|
||||
"SUCCESS_DATETIME_RETRIEVED",
|
||||
map[string]any{
|
||||
"value": value,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimDatetimeValidate
|
||||
// Function Purpose: Validate utility inputs and configuration.
|
||||
func obrimDatetimeValidate(datetimeType string, config map[string]any) error {
|
||||
if datetimeType != "local" && datetimeType != "trusted" {
|
||||
return errors.New("INVALID_TYPE")
|
||||
}
|
||||
|
||||
formatValue, exists := config["format"]
|
||||
if !exists {
|
||||
return errors.New("INVALID_FORMAT")
|
||||
}
|
||||
|
||||
formatString := fmt.Sprintf("%v", formatValue)
|
||||
|
||||
if !obrimDatetimePatternValidate(formatString) {
|
||||
return errors.New("INVALID_FORMAT")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Function Name: obrimDatetimePatternValidate
|
||||
// Function Purpose: Validate supported format patterns.
|
||||
func obrimDatetimePatternValidate(pattern string) bool {
|
||||
if pattern == "timestampsec" || pattern == "timestampmil" {
|
||||
return true
|
||||
}
|
||||
|
||||
_, exists := obrimDatetimePatternMap[pattern]
|
||||
return exists
|
||||
}
|
||||
|
||||
// Function Name: obrimDatetimePatternResolve
|
||||
// Function Purpose: Resolve supported format patterns into internal formatting layouts.
|
||||
func obrimDatetimePatternResolve(pattern string) (string, error) {
|
||||
layout, exists := obrimDatetimePatternMap[pattern]
|
||||
if !exists {
|
||||
return "", errors.New("INVALID_FORMAT")
|
||||
}
|
||||
|
||||
return layout, nil
|
||||
}
|
||||
|
||||
// Function Name: obrimDatetimeFormatApply
|
||||
// Function Purpose: Generate the final formatted value.
|
||||
func obrimDatetimeFormatApply(currentTime time.Time, pattern string) (string, error) {
|
||||
switch pattern {
|
||||
case "timestampsec":
|
||||
return strconv.FormatInt(currentTime.Unix(), 10), nil
|
||||
|
||||
case "timestampmil":
|
||||
return strconv.FormatInt(currentTime.UnixMilli(), 10), nil
|
||||
}
|
||||
|
||||
layout, err := obrimDatetimePatternResolve(pattern)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return currentTime.Format(layout), nil
|
||||
}
|
||||
|
||||
// Function Name: obrimDatetimeResponse
|
||||
// Function Purpose: Build standardized utility response objects.
|
||||
func obrimDatetimeResponse(statusValue bool, code string, payload any) map[string]any {
|
||||
return map[string]any{
|
||||
"status": statusValue,
|
||||
"code": code,
|
||||
"payload": payload,
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimDatetimeLocal
|
||||
// Function Purpose: Retrieve current date and time from the host system clock.
|
||||
func obrimDatetimeLocal() (time.Time, error) {
|
||||
_, _ = retriever.ObrimRetriever(
|
||||
"datetime",
|
||||
map[string]any{
|
||||
"source": "local",
|
||||
},
|
||||
)
|
||||
|
||||
return time.Now(), nil
|
||||
}
|
||||
|
||||
// Function Name: obrimDatetimeTrusted
|
||||
// Function Purpose: Retrieve current date and time from the framework-managed NTP pool source.
|
||||
func obrimDatetimeTrusted() (time.Time, error) {
|
||||
return obrimDatetimeTrustedSync()
|
||||
}
|
||||
|
||||
// Function Name: obrimDatetimeTrustedSync
|
||||
// Function Purpose: Synchronize and retrieve trusted time from the NTP source.
|
||||
func obrimDatetimeTrustedSync() (time.Time, error) {
|
||||
_, _ = retriever.ObrimRetriever(
|
||||
"datetime",
|
||||
map[string]any{
|
||||
"source": "trusted",
|
||||
},
|
||||
)
|
||||
|
||||
return ntp.Time("pool.ntp.org")
|
||||
}
|
||||
@ -0,0 +1,529 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Filesystem
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - Filesystem
|
||||
|
|
||||
| Purpose:
|
||||
| - Execute deterministic filesystem operations through a unified interface.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Validate operation type before execution.
|
||||
| - Validate configuration before execution.
|
||||
| - Execute exactly one operation per invocation.
|
||||
| - Return structured results.
|
||||
| - Remain OS-agnostic.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimFilesystem("list", config)
|
||||
| - ObrimFilesystem("create", config)
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
| - OpenAI
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package filesystem
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go/module/name/essential/visible/service/helper/log"
|
||||
"go/module/name/essential/visible/service/helper/status"
|
||||
)
|
||||
|
||||
type filesystemResult struct {
|
||||
Status bool `json:"status"`
|
||||
Code string `json:"code"`
|
||||
Payload map[string]any `json:"payload"`
|
||||
}
|
||||
|
||||
// Function Name: ObrimFilesystem
|
||||
// Function Purpose: Execute a filesystem operation and return a structured result.
|
||||
func ObrimFilesystem(operationType string, config map[string]any) map[string]any {
|
||||
log.ObrimLog("INIT", fmt.Sprintf("filesystem operation=%s", operationType))
|
||||
|
||||
if result := obrimFilesystemValidate(operationType, config); result != nil {
|
||||
status.ObrimStatus("ERROR", result["code"].(string))
|
||||
return result
|
||||
}
|
||||
|
||||
resolvedPath, err := obrimFilesystemResolve(config)
|
||||
if err != nil {
|
||||
status.ObrimStatus("ERROR", err.Error())
|
||||
|
||||
return obrimFilesystemPayload(
|
||||
false,
|
||||
"FAILED_PATH_RESOLUTION",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
config["_resolved_path"] = resolvedPath
|
||||
|
||||
switch operationType {
|
||||
case "list":
|
||||
return obrimFilesystemList(config)
|
||||
|
||||
case "check":
|
||||
return obrimFilesystemCheck(config)
|
||||
|
||||
case "create":
|
||||
return obrimFilesystemCreate(config)
|
||||
|
||||
case "delete":
|
||||
return obrimFilesystemDelete(config)
|
||||
|
||||
case "permission":
|
||||
return obrimFilesystemPermission(config)
|
||||
}
|
||||
|
||||
return obrimFilesystemPayload(false, "FAILED_UNSUPPORTED_OPERATION", nil)
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemValidate
|
||||
// Function Purpose: Validate operation type, configuration, and supported keys.
|
||||
func obrimFilesystemValidate(operationType string, config map[string]any) map[string]any {
|
||||
validTypes := map[string]bool{
|
||||
"list": true,
|
||||
"check": true,
|
||||
"create": true,
|
||||
"delete": true,
|
||||
"permission": true,
|
||||
}
|
||||
|
||||
if !validTypes[operationType] {
|
||||
return obrimFilesystemPayload(false, "FAILED_INVALID_TYPE", nil)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemResolve
|
||||
// Function Purpose: Resolve and normalize filesystem paths.
|
||||
func obrimFilesystemResolve(config map[string]any) (string, error) {
|
||||
basePath := ""
|
||||
|
||||
strategy, _ := config["strategy"].(string)
|
||||
|
||||
switch strategy {
|
||||
case "user":
|
||||
currentUser, err := user.Current()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
basePath = currentUser.HomeDir
|
||||
|
||||
case "custom":
|
||||
basePath, _ = config["base"].(string)
|
||||
|
||||
default:
|
||||
basePath, _ = config["base"].(string)
|
||||
}
|
||||
|
||||
name, _ := config["name"].(string)
|
||||
|
||||
if basePath == "" && name == "" {
|
||||
basePath = "."
|
||||
}
|
||||
|
||||
return filepath.Clean(filepath.Join(basePath, name)), nil
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemPayload
|
||||
// Function Purpose: Build standardized output payload structures.
|
||||
func obrimFilesystemPayload(statusValue bool, code string, payload map[string]any) map[string]any {
|
||||
if !statusValue {
|
||||
payload = nil
|
||||
}
|
||||
|
||||
return map[string]any{
|
||||
"status": statusValue,
|
||||
"code": code,
|
||||
"payload": payload,
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemEntityType
|
||||
// Function Purpose: Determine filesystem entity type.
|
||||
func obrimFilesystemEntityType(path string) string {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
return "directory"
|
||||
}
|
||||
|
||||
return "file"
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemPermissionValidate
|
||||
// Function Purpose: Validate permission specifications before execution.
|
||||
func obrimFilesystemPermissionValidate(permission string) error {
|
||||
if permission == "" {
|
||||
return fmt.Errorf("invalid permission")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemList
|
||||
// Function Purpose: Execute filesystem listing operations.
|
||||
func obrimFilesystemList(config map[string]any) map[string]any {
|
||||
entries, err := obrimFilesystemListTraverse(config)
|
||||
if err != nil {
|
||||
return obrimFilesystemPayload(false, "FAILED_LIST", nil)
|
||||
}
|
||||
|
||||
entries = obrimFilesystemListFilter(entries, config)
|
||||
entries = obrimFilesystemListSort(entries, config)
|
||||
|
||||
payload := map[string]any{
|
||||
"entries": entries,
|
||||
"total": len(entries),
|
||||
"recursive": config["recursive"] == true,
|
||||
"base_path": config["_resolved_path"],
|
||||
}
|
||||
|
||||
status.ObrimStatus("SUCCESS", "Filesystem listing completed.")
|
||||
|
||||
return obrimFilesystemPayload(true, "SUCCESS_LIST", payload)
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemListTraverse
|
||||
// Function Purpose: Traverse filesystem entities according to listing configuration.
|
||||
func obrimFilesystemListTraverse(config map[string]any) ([]map[string]any, error) {
|
||||
// Logic:
|
||||
var results []map[string]any
|
||||
|
||||
// Logic:
|
||||
resolvedPath := config["_resolved_path"].(string)
|
||||
|
||||
// Logic:
|
||||
recursive, _ := config["recursive"].(bool)
|
||||
|
||||
if recursive {
|
||||
err := filepath.WalkDir(
|
||||
resolvedPath,
|
||||
func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
results = append(results, map[string]any{
|
||||
"path": path,
|
||||
"name": d.Name(),
|
||||
})
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
|
||||
return results, err
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(resolvedPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
results = append(results, map[string]any{
|
||||
"path": filepath.Join(resolvedPath, entry.Name()),
|
||||
"name": entry.Name(),
|
||||
})
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemListFilter
|
||||
// Function Purpose: Apply entity and pattern filtering.
|
||||
func obrimFilesystemListFilter(entries []map[string]any, config map[string]any) []map[string]any {
|
||||
// Logic:
|
||||
var filtered []map[string]any
|
||||
|
||||
// Logic:
|
||||
pattern, _ := config["filter_pattern"].(string)
|
||||
|
||||
// Logic:
|
||||
entity, _ := config["entity"].(string)
|
||||
|
||||
for _, entry := range entries {
|
||||
path := entry["path"].(string)
|
||||
|
||||
if pattern != "" && !strings.Contains(filepath.Base(path), pattern) {
|
||||
continue
|
||||
}
|
||||
|
||||
if entity != "" && obrimFilesystemEntityType(path) != entity {
|
||||
continue
|
||||
}
|
||||
|
||||
filtered = append(filtered, entry)
|
||||
}
|
||||
|
||||
return filtered
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemListSort
|
||||
// Function Purpose: Apply result sorting behavior.
|
||||
func obrimFilesystemListSort(entries []map[string]any, config map[string]any) []map[string]any {
|
||||
sortBy, _ := config["sort_by"].(string)
|
||||
sortOrder, _ := config["sort_order"].(string)
|
||||
|
||||
sort.Slice(entries, func(i, j int) bool {
|
||||
left := fmt.Sprintf("%v", entries[i][sortBy])
|
||||
right := fmt.Sprintf("%v", entries[j][sortBy])
|
||||
|
||||
if sortOrder == "desc" {
|
||||
return left > right
|
||||
}
|
||||
|
||||
return left < right
|
||||
})
|
||||
|
||||
return entries
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemCheck
|
||||
// Function Purpose: Execute filesystem validation operations.
|
||||
func obrimFilesystemCheck(config map[string]any) map[string]any {
|
||||
path := config["_resolved_path"].(string)
|
||||
|
||||
_, err := os.Stat(path)
|
||||
|
||||
payload := map[string]any{
|
||||
"path": path,
|
||||
"exists": err == nil,
|
||||
"entity": obrimFilesystemEntityType(path),
|
||||
"readable": obrimFilesystemCheckAccess(path, "read"),
|
||||
"writable": obrimFilesystemCheckAccess(path, "write"),
|
||||
}
|
||||
|
||||
return obrimFilesystemPayload(true, "SUCCESS_CHECK", payload)
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemCheckAccess
|
||||
// Function Purpose: Verify filesystem accessibility requirements.
|
||||
func obrimFilesystemCheckAccess(path string, mode string) bool {
|
||||
if mode == "read" {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
_ = file.Close()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
file, err := os.OpenFile(path, os.O_WRONLY, 0)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
_ = file.Close()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemCreate
|
||||
// Function Purpose: Execute filesystem entity creation operations.
|
||||
func obrimFilesystemCreate(config map[string]any) map[string]any {
|
||||
entity, _ := config["entity"].(string)
|
||||
|
||||
switch entity {
|
||||
case "file":
|
||||
return obrimFilesystemCreateFile(config)
|
||||
|
||||
case "directory":
|
||||
return obrimFilesystemCreateDirectory(config)
|
||||
}
|
||||
|
||||
return obrimFilesystemPayload(false, "FAILED_CREATE", nil)
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemCreateFile
|
||||
// Function Purpose: Create a filesystem file.
|
||||
func obrimFilesystemCreateFile(config map[string]any) map[string]any {
|
||||
path := config["_resolved_path"].(string)
|
||||
|
||||
_ = os.MkdirAll(filepath.Dir(path), 0755)
|
||||
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
return obrimFilesystemPayload(false, "FAILED_CREATE_FILE", nil)
|
||||
}
|
||||
|
||||
_ = file.Close()
|
||||
|
||||
payload := map[string]any{
|
||||
"path": path,
|
||||
"entity": "file",
|
||||
"hidden": config["hidden"] == true,
|
||||
"created": true,
|
||||
}
|
||||
|
||||
return obrimFilesystemPayload(true, "SUCCESS_CREATE_FILE", payload)
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemCreateDirectory
|
||||
// Function Purpose: Create a filesystem directory.
|
||||
func obrimFilesystemCreateDirectory(config map[string]any) map[string]any {
|
||||
path := config["_resolved_path"].(string)
|
||||
|
||||
if err := os.MkdirAll(path, 0755); err != nil {
|
||||
return obrimFilesystemPayload(false, "FAILED_CREATE_DIRECTORY", nil)
|
||||
}
|
||||
|
||||
payload := map[string]any{
|
||||
"path": path,
|
||||
"entity": "directory",
|
||||
"hidden": config["hidden"] == true,
|
||||
"created": true,
|
||||
}
|
||||
|
||||
return obrimFilesystemPayload(true, "SUCCESS_CREATE_DIRECTORY", payload)
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemDelete
|
||||
// Function Purpose: Execute filesystem entity deletion operations.
|
||||
func obrimFilesystemDelete(config map[string]any) map[string]any {
|
||||
entity := obrimFilesystemEntityType(config["_resolved_path"].(string))
|
||||
|
||||
if entity == "file" {
|
||||
return obrimFilesystemDeleteFile(config)
|
||||
}
|
||||
|
||||
return obrimFilesystemDeleteDirectory(config)
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemDeleteFile
|
||||
// Function Purpose: Delete a filesystem file.
|
||||
func obrimFilesystemDeleteFile(config map[string]any) map[string]any {
|
||||
path := config["_resolved_path"].(string)
|
||||
|
||||
if err := os.Remove(path); err != nil {
|
||||
return obrimFilesystemPayload(false, "FAILED_DELETE_FILE", nil)
|
||||
}
|
||||
|
||||
return obrimFilesystemPayload(true, "SUCCESS_DELETE_FILE", map[string]any{
|
||||
"path": path,
|
||||
"entity": "file",
|
||||
"deleted": true,
|
||||
})
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemDeleteDirectory
|
||||
// Function Purpose: Delete a filesystem directory.
|
||||
func obrimFilesystemDeleteDirectory(config map[string]any) map[string]any {
|
||||
path := config["_resolved_path"].(string)
|
||||
|
||||
recursive, _ := config["recursive"].(bool)
|
||||
|
||||
var err error
|
||||
|
||||
if recursive {
|
||||
err = os.RemoveAll(path)
|
||||
} else {
|
||||
err = os.Remove(path)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return obrimFilesystemPayload(false, "FAILED_DELETE_DIRECTORY", nil)
|
||||
}
|
||||
|
||||
return obrimFilesystemPayload(true, "SUCCESS_DELETE_DIRECTORY", map[string]any{
|
||||
"path": path,
|
||||
"entity": "directory",
|
||||
"deleted": true,
|
||||
})
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemPermission
|
||||
// Function Purpose: Execute filesystem permission operations.
|
||||
func obrimFilesystemPermission(config map[string]any) map[string]any {
|
||||
mode, _ := config["mode"].(string)
|
||||
|
||||
switch mode {
|
||||
case "read":
|
||||
return obrimFilesystemPermissionRead(config)
|
||||
|
||||
case "write":
|
||||
return obrimFilesystemPermissionWrite(config)
|
||||
}
|
||||
|
||||
return obrimFilesystemPayload(false, "FAILED_PERMISSION", nil)
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemPermissionRead
|
||||
// Function Purpose: Retrieve filesystem permissions.
|
||||
func obrimFilesystemPermissionRead(config map[string]any) map[string]any {
|
||||
path := config["_resolved_path"].(string)
|
||||
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return obrimFilesystemPayload(false, "FAILED_PERMISSION_READ", nil)
|
||||
}
|
||||
|
||||
return obrimFilesystemPayload(true, "SUCCESS_PERMISSION_READ", map[string]any{
|
||||
"path": path,
|
||||
"permission": info.Mode().Perm().String(),
|
||||
"mode": "read",
|
||||
"updated": false,
|
||||
})
|
||||
}
|
||||
|
||||
// Function Name: obrimFilesystemPermissionWrite
|
||||
// Function Purpose: Update filesystem permissions.
|
||||
func obrimFilesystemPermissionWrite(config map[string]any) map[string]any {
|
||||
path := config["_resolved_path"].(string)
|
||||
|
||||
permission, _ := config["permission"].(string)
|
||||
|
||||
if err := obrimFilesystemPermissionValidate(permission); err != nil {
|
||||
return obrimFilesystemPayload(false, "FAILED_INVALID_PERMISSION", nil)
|
||||
}
|
||||
|
||||
var permissionValue fs.FileMode
|
||||
|
||||
_, err := fmt.Sscanf(permission, "%o", &permissionValue)
|
||||
if err != nil {
|
||||
return obrimFilesystemPayload(false, "FAILED_INVALID_PERMISSION", nil)
|
||||
}
|
||||
|
||||
if err := os.Chmod(path, permissionValue); err != nil {
|
||||
return obrimFilesystemPayload(false, "FAILED_PERMISSION_WRITE", nil)
|
||||
}
|
||||
|
||||
return obrimFilesystemPayload(true, "SUCCESS_PERMISSION_WRITE", map[string]any{
|
||||
"path": path,
|
||||
"permission": permission,
|
||||
"mode": "write",
|
||||
"updated": true,
|
||||
"timestamp": time.Now().UTC(),
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,442 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Hash
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - Hash
|
||||
|
|
||||
| Purpose:
|
||||
| - Generate and verify cryptographic hash values using standard or
|
||||
| salted hashing methods.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Accept exactly two primary parameters: type and config.
|
||||
| - Validate all inputs before processing.
|
||||
| - Return all results through the standard output structure.
|
||||
| - Never panic or terminate execution.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimHash("calculate", config)
|
||||
| - ObrimHash("compare", config)
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
| - Scionite
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package hash
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"go/module/name/essential/external/service/helper/log"
|
||||
"go/module/name/essential/external/service/helper/retriever"
|
||||
"go/module/name/essential/external/service/helper/status"
|
||||
)
|
||||
|
||||
const (
|
||||
obrimHashTypeCalculate = "calculate"
|
||||
obrimHashTypeCompare = "compare"
|
||||
|
||||
obrimHashModeStandard = "standard"
|
||||
obrimHashModeSalted = "salted"
|
||||
)
|
||||
|
||||
var obrimHashSupportedAlgorithms = map[string]bool{
|
||||
"sha256": true,
|
||||
"sha512": true,
|
||||
"salted_sha256": true,
|
||||
"salted_sha512": true,
|
||||
}
|
||||
|
||||
var obrimHashSupportedConfigKeys = map[string]bool{
|
||||
"mode": true,
|
||||
"algorithm": true,
|
||||
"value": true,
|
||||
"hash": true,
|
||||
"salt": true,
|
||||
}
|
||||
|
||||
// Function Name: ObrimHash
|
||||
// Function Purpose: Process hash generation and verification requests.
|
||||
func ObrimHash(
|
||||
hashType string,
|
||||
config map[string]any,
|
||||
) map[string]any {
|
||||
_, _ = retriever.ObrimRetriever, status.ObrimStatus
|
||||
log.ObrimLog("INIT", "Hash utility request received.")
|
||||
|
||||
if !obrimHashValidateType(hashType) {
|
||||
return obrimHashBuildErrorPayload("FAILED_INVALID_TYPE")
|
||||
}
|
||||
|
||||
if !obrimHashValidateConfig(hashType, config) {
|
||||
return obrimHashBuildErrorPayload("FAILED_INVALID_CONFIG")
|
||||
}
|
||||
|
||||
mode := config["mode"].(string)
|
||||
|
||||
if !obrimHashValidateMode(mode) {
|
||||
return obrimHashBuildErrorPayload("FAILED_INVALID_MODE")
|
||||
}
|
||||
|
||||
algorithm := config["algorithm"].(string)
|
||||
|
||||
if !obrimHashValidateAlgorithm(algorithm) {
|
||||
return obrimHashBuildErrorPayload("FAILED_INVALID_ALGORITHM")
|
||||
}
|
||||
|
||||
switch hashType {
|
||||
case obrimHashTypeCalculate:
|
||||
return obrimHashCalculate(config)
|
||||
|
||||
case obrimHashTypeCompare:
|
||||
return obrimHashCompare(config)
|
||||
|
||||
default:
|
||||
return obrimHashBuildErrorPayload("FAILED_INVALID_TYPE")
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimHashValidateType
|
||||
// Function Purpose: Validate operation type.
|
||||
func obrimHashValidateType(hashType string) bool {
|
||||
return hashType == obrimHashTypeCalculate ||
|
||||
hashType == obrimHashTypeCompare
|
||||
}
|
||||
|
||||
// Function Name: obrimHashValidateMode
|
||||
// Function Purpose: Validate hashing mode.
|
||||
func obrimHashValidateMode(mode string) bool {
|
||||
return mode == obrimHashModeStandard ||
|
||||
mode == obrimHashModeSalted
|
||||
}
|
||||
|
||||
// Function Name: obrimHashValidateConfig
|
||||
// Function Purpose: Validate configuration keys and values.
|
||||
func obrimHashValidateConfig(
|
||||
hashType string,
|
||||
config map[string]any,
|
||||
) bool {
|
||||
if config == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for key := range config {
|
||||
if !obrimHashSupportedConfigKeys[key] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
requiredKeys := []string{
|
||||
"mode",
|
||||
"algorithm",
|
||||
"value",
|
||||
}
|
||||
|
||||
for _, key := range requiredKeys {
|
||||
value, exists := config[key]
|
||||
if !exists || value == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
stringValue, ok := value.(string)
|
||||
if !ok || stringValue == "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
mode := config["mode"].(string)
|
||||
|
||||
if hashType == obrimHashTypeCompare {
|
||||
hashValue, exists := config["hash"]
|
||||
if !exists || hashValue == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
hashString, ok := hashValue.(string)
|
||||
if !ok || hashString == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if mode == obrimHashModeSalted {
|
||||
saltValue, exists := config["salt"]
|
||||
if !exists || saltValue == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
saltString, ok := saltValue.(string)
|
||||
if !ok || saltString == "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if mode == obrimHashModeStandard {
|
||||
if _, exists := config["salt"]; exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Function Name: obrimHashValidateAlgorithm
|
||||
// Function Purpose: Validate hashing algorithm selection.
|
||||
func obrimHashValidateAlgorithm(algorithm string) bool {
|
||||
return obrimHashSupportedAlgorithms[algorithm]
|
||||
}
|
||||
|
||||
// Function Name: obrimHashGenerateHash
|
||||
// Function Purpose: Execute the selected hashing algorithm.
|
||||
func obrimHashGenerateHash(
|
||||
algorithm string,
|
||||
value string,
|
||||
salt string,
|
||||
) (string, bool) {
|
||||
input := value
|
||||
|
||||
switch algorithm {
|
||||
case "salted_sha256", "salted_sha512":
|
||||
input = value + salt
|
||||
}
|
||||
|
||||
switch algorithm {
|
||||
case "sha256", "salted_sha256":
|
||||
hash := sha256.Sum256([]byte(input))
|
||||
return hex.EncodeToString(hash[:]), true
|
||||
|
||||
case "sha512", "salted_sha512":
|
||||
hash := sha512.Sum512([]byte(input))
|
||||
return hex.EncodeToString(hash[:]), true
|
||||
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimHashBuildSuccessPayload
|
||||
// Function Purpose: Construct success response payloads.
|
||||
func obrimHashBuildSuccessPayload(
|
||||
code string,
|
||||
payload map[string]any,
|
||||
) map[string]any {
|
||||
return map[string]any{
|
||||
"status": true,
|
||||
"code": code,
|
||||
"payload": payload,
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimHashBuildErrorPayload
|
||||
// Function Purpose: Construct error response payloads.
|
||||
func obrimHashBuildErrorPayload(code string) map[string]any {
|
||||
return map[string]any{
|
||||
"status": false,
|
||||
"code": code,
|
||||
"payload": nil,
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimHashCalculate
|
||||
// Function Purpose: Process hash generation requests.
|
||||
func obrimHashCalculate(
|
||||
config map[string]any,
|
||||
) map[string]any {
|
||||
mode := config["mode"].(string)
|
||||
|
||||
switch mode {
|
||||
case obrimHashModeStandard:
|
||||
return obrimHashCalculateStandard(config)
|
||||
|
||||
case obrimHashModeSalted:
|
||||
return obrimHashCalculateSalted(config)
|
||||
|
||||
default:
|
||||
return obrimHashBuildErrorPayload("FAILED_INVALID_MODE")
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimHashCalculateStandard
|
||||
// Function Purpose: Generate a deterministic hash.
|
||||
func obrimHashCalculateStandard(
|
||||
config map[string]any,
|
||||
) map[string]any {
|
||||
hashValue, ok := obrimHashGenerateHash(
|
||||
config["algorithm"].(string),
|
||||
config["value"].(string),
|
||||
"",
|
||||
)
|
||||
|
||||
if !ok {
|
||||
return obrimHashBuildErrorPayload("FAILED_HASH_GENERATION")
|
||||
}
|
||||
|
||||
return obrimHashBuildSuccessPayload(
|
||||
"SUCCESS_HASH_CALCULATED",
|
||||
map[string]any{
|
||||
"algorithm": config["algorithm"].(string),
|
||||
"hash": hashValue,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimHashCalculateSalted
|
||||
// Function Purpose: Generate a salted hash and salt pair.
|
||||
func obrimHashCalculateSalted(
|
||||
config map[string]any,
|
||||
) map[string]any {
|
||||
// Logic: Resolve salt.
|
||||
salt := ""
|
||||
|
||||
if value, exists := config["salt"]; exists {
|
||||
salt = value.(string)
|
||||
}
|
||||
|
||||
if salt == "" {
|
||||
generatedSalt, ok := obrimHashGenerateSalt()
|
||||
if !ok {
|
||||
return obrimHashBuildErrorPayload("FAILED_SALT_GENERATION")
|
||||
}
|
||||
|
||||
salt = generatedSalt
|
||||
}
|
||||
|
||||
hashValue, ok := obrimHashGenerateHash(
|
||||
config["algorithm"].(string),
|
||||
config["value"].(string),
|
||||
salt,
|
||||
)
|
||||
|
||||
if !ok {
|
||||
return obrimHashBuildErrorPayload("FAILED_HASH_GENERATION")
|
||||
}
|
||||
|
||||
return obrimHashBuildSuccessPayload(
|
||||
"SUCCESS_HASH_CALCULATED",
|
||||
map[string]any{
|
||||
"algorithm": config["algorithm"].(string),
|
||||
"hash": hashValue,
|
||||
"salt": salt,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimHashGenerateSalt
|
||||
// Function Purpose: Generate a cryptographically secure salt.
|
||||
func obrimHashGenerateSalt() (string, bool) {
|
||||
// Logic: Generate secure random bytes.
|
||||
saltBytes := make([]byte, 32)
|
||||
|
||||
if _, err := rand.Read(saltBytes); err != nil {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return hex.EncodeToString(saltBytes), true
|
||||
}
|
||||
|
||||
// Function Name: obrimHashCompare
|
||||
// Function Purpose: Process hash verification requests.
|
||||
func obrimHashCompare(
|
||||
config map[string]any,
|
||||
) map[string]any {
|
||||
mode := config["mode"].(string)
|
||||
|
||||
switch mode {
|
||||
case obrimHashModeStandard:
|
||||
return obrimHashCompareStandard(config)
|
||||
|
||||
case obrimHashModeSalted:
|
||||
return obrimHashCompareSalted(config)
|
||||
|
||||
default:
|
||||
return obrimHashBuildErrorPayload("FAILED_INVALID_MODE")
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimHashCompareStandard
|
||||
// Function Purpose: Regenerate a standard hash for verification.
|
||||
func obrimHashCompareStandard(
|
||||
config map[string]any,
|
||||
) map[string]any {
|
||||
regeneratedHash, ok := obrimHashGenerateHash(
|
||||
config["algorithm"].(string),
|
||||
config["value"].(string),
|
||||
"",
|
||||
)
|
||||
|
||||
if !ok {
|
||||
return obrimHashBuildErrorPayload("FAILED_HASH_GENERATION")
|
||||
}
|
||||
|
||||
matched := obrimHashVerify(
|
||||
regeneratedHash,
|
||||
config["hash"].(string),
|
||||
)
|
||||
|
||||
return obrimHashBuildSuccessPayload(
|
||||
"SUCCESS_HASH_COMPARED",
|
||||
map[string]any{
|
||||
"algorithm": config["algorithm"].(string),
|
||||
"matched": matched,
|
||||
"hash": config["hash"].(string),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimHashCompareSalted
|
||||
// Function Purpose: Regenerate a salted hash for verification.
|
||||
func obrimHashCompareSalted(
|
||||
config map[string]any,
|
||||
) map[string]any {
|
||||
salt := config["salt"].(string)
|
||||
|
||||
regeneratedHash, ok := obrimHashGenerateHash(
|
||||
config["algorithm"].(string),
|
||||
config["value"].(string),
|
||||
salt,
|
||||
)
|
||||
|
||||
if !ok {
|
||||
return obrimHashBuildErrorPayload("FAILED_HASH_GENERATION")
|
||||
}
|
||||
|
||||
matched := obrimHashVerify(
|
||||
regeneratedHash,
|
||||
config["hash"].(string),
|
||||
)
|
||||
|
||||
return obrimHashBuildSuccessPayload(
|
||||
"SUCCESS_HASH_COMPARED",
|
||||
map[string]any{
|
||||
"algorithm": config["algorithm"].(string),
|
||||
"matched": matched,
|
||||
"hash": config["hash"].(string),
|
||||
"salt": salt,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimHashVerify
|
||||
// Function Purpose: Compare regenerated and supplied hash values.
|
||||
func obrimHashVerify(
|
||||
regeneratedHash string,
|
||||
suppliedHash string,
|
||||
) bool {
|
||||
return strings.Compare(regeneratedHash, suppliedHash) == 0
|
||||
}
|
||||
@ -0,0 +1,359 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Key
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - Key
|
||||
|
|
||||
| Purpose:
|
||||
| - Generate cryptographic key material through a type-driven dispatch
|
||||
| model with strict validation, schema isolation, and centralized
|
||||
| orchestration.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Validate all inputs before generation.
|
||||
| - Enforce strict schema isolation.
|
||||
| - Reject unsupported configuration fields.
|
||||
| - Prevent key exposure on failure paths.
|
||||
| - Return standardized responses.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimKey("symmetric", map[string]any{
|
||||
| "algorithm": "aes",
|
||||
| "key_size": 256,
|
||||
| })
|
||||
|
|
||||
| - ObrimKey("asymmetric", map[string]any{
|
||||
| "algorithm": "ecc",
|
||||
| })
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
| - Scionite
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package key
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go/module/name/essential/external/service/helper/log"
|
||||
"go/module/name/essential/external/service/helper/retriever"
|
||||
"go/module/name/essential/external/service/helper/status"
|
||||
)
|
||||
|
||||
// Function Name: ObrimKey
|
||||
// Function Purpose: Dispatch key generation requests and orchestrate validation, generation, and response construction.
|
||||
func ObrimKey(keyType string, config map[string]any) map[string]any {
|
||||
log.ObrimLog("INIT", "Key generation request received.")
|
||||
|
||||
if result := obrimKeyValidate(keyType, config); result != nil {
|
||||
return result
|
||||
}
|
||||
|
||||
result := obrimKeyDispatch(keyType, config)
|
||||
|
||||
if statusValue, ok := result["status"].(bool); ok && statusValue {
|
||||
status.ObrimStatus("SUCCESS", "Key generation completed.")
|
||||
log.ObrimLog("SUCCESS", "Key generation completed successfully.")
|
||||
return result
|
||||
}
|
||||
|
||||
status.ObrimStatus("ERROR", "Key generation failed.")
|
||||
log.ObrimLog("ERROR", "Key generation failed.")
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyValidate
|
||||
// Function Purpose: Validate common request structure and schema integrity.
|
||||
func obrimKeyValidate(keyType string, config map[string]any) map[string]any {
|
||||
log.ObrimLog("VALIDATION", "Validating key request.")
|
||||
|
||||
if strings.TrimSpace(keyType) == "" {
|
||||
return obrimKeyBuildError("FAILED_TYPE_REQUIRED")
|
||||
}
|
||||
|
||||
if config == nil {
|
||||
return obrimKeyBuildError("FAILED_CONFIG_REQUIRED")
|
||||
}
|
||||
|
||||
normalizedType := strings.ToLower(strings.TrimSpace(keyType))
|
||||
|
||||
switch normalizedType {
|
||||
case "symmetric":
|
||||
return obrimKeyValidateSymmetricConfig(config)
|
||||
|
||||
case "asymmetric":
|
||||
return obrimKeyValidateAsymmetricConfig(config)
|
||||
|
||||
default:
|
||||
return obrimKeyBuildError("FAILED_UNSUPPORTED_TYPE")
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyDispatch
|
||||
// Function Purpose: Route execution to the appropriate cryptographic workflow.
|
||||
func obrimKeyDispatch(keyType string, config map[string]any) map[string]any {
|
||||
normalizedType := strings.ToLower(strings.TrimSpace(keyType))
|
||||
|
||||
switch normalizedType {
|
||||
case "symmetric":
|
||||
return obrimKeyGenerateSymmetric(config)
|
||||
|
||||
case "asymmetric":
|
||||
return obrimKeyGenerateAsymmetric(config)
|
||||
|
||||
default:
|
||||
return obrimKeyBuildError("FAILED_UNSUPPORTED_TYPE")
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyValidateSymmetricConfig
|
||||
// Function Purpose: Validate symmetric configuration values.
|
||||
func obrimKeyValidateSymmetricConfig(config map[string]any) map[string]any {
|
||||
if len(config) != 2 {
|
||||
return obrimKeyBuildError("FAILED_INVALID_CONFIGURATION")
|
||||
}
|
||||
|
||||
// Logic:
|
||||
for key := range config {
|
||||
if key != "algorithm" && key != "key_size" {
|
||||
return obrimKeyBuildError("FAILED_UNSUPPORTED_CONFIGURATION_FIELD")
|
||||
}
|
||||
}
|
||||
|
||||
algorithmValue, exists := config["algorithm"]
|
||||
if !exists {
|
||||
return obrimKeyBuildError("FAILED_ALGORITHM_REQUIRED")
|
||||
}
|
||||
|
||||
algorithm, ok := algorithmValue.(string)
|
||||
if !ok {
|
||||
return obrimKeyBuildError("FAILED_INVALID_ALGORITHM")
|
||||
}
|
||||
|
||||
if strings.ToLower(strings.TrimSpace(algorithm)) != "aes" {
|
||||
return obrimKeyBuildError("FAILED_UNSUPPORTED_ALGORITHM")
|
||||
}
|
||||
|
||||
keySizeValue, exists := config["key_size"]
|
||||
if !exists {
|
||||
return obrimKeyBuildError("FAILED_KEY_SIZE_REQUIRED")
|
||||
}
|
||||
|
||||
var keySize int
|
||||
|
||||
switch value := keySizeValue.(type) {
|
||||
case int:
|
||||
keySize = value
|
||||
case int32:
|
||||
keySize = int(value)
|
||||
case int64:
|
||||
keySize = int(value)
|
||||
case float64:
|
||||
keySize = int(value)
|
||||
default:
|
||||
return obrimKeyBuildError("FAILED_INVALID_KEY_SIZE")
|
||||
}
|
||||
|
||||
switch keySize {
|
||||
case 128, 192, 256:
|
||||
return nil
|
||||
default:
|
||||
return obrimKeyBuildError("FAILED_UNSUPPORTED_KEY_SIZE")
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyValidateAsymmetricConfig
|
||||
// Function Purpose: Validate asymmetric configuration values.
|
||||
func obrimKeyValidateAsymmetricConfig(config map[string]any) map[string]any {
|
||||
if len(config) != 1 {
|
||||
return obrimKeyBuildError("FAILED_INVALID_CONFIGURATION")
|
||||
}
|
||||
|
||||
// Logic:
|
||||
for key := range config {
|
||||
if key != "algorithm" {
|
||||
return obrimKeyBuildError("FAILED_UNSUPPORTED_CONFIGURATION_FIELD")
|
||||
}
|
||||
}
|
||||
|
||||
algorithmValue, exists := config["algorithm"]
|
||||
if !exists {
|
||||
return obrimKeyBuildError("FAILED_ALGORITHM_REQUIRED")
|
||||
}
|
||||
|
||||
algorithm, ok := algorithmValue.(string)
|
||||
if !ok {
|
||||
return obrimKeyBuildError("FAILED_INVALID_ALGORITHM")
|
||||
}
|
||||
|
||||
if strings.ToLower(strings.TrimSpace(algorithm)) != "ecc" {
|
||||
return obrimKeyBuildError("FAILED_UNSUPPORTED_ALGORITHM")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyGenerateSymmetric
|
||||
// Function Purpose: Generate symmetric key material.
|
||||
func obrimKeyGenerateSymmetric(config map[string]any) map[string]any {
|
||||
normalizedConfig := obrimKeyNormalizeSymmetricConfig(config)
|
||||
|
||||
payload, err := obrimKeyGenerateAES(normalizedConfig)
|
||||
if err != nil {
|
||||
log.ObrimLog("ERROR", "AES key generation failed.")
|
||||
return obrimKeyBuildError("FAILED_GENERATION")
|
||||
}
|
||||
|
||||
return map[string]any{
|
||||
"status": true,
|
||||
"code": "SUCCESS_KEY_GENERATED",
|
||||
"payload": obrimKeyBuildPayload(
|
||||
payload,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyGenerateAES
|
||||
// Function Purpose: Generate AES key material.
|
||||
func obrimKeyGenerateAES(config map[string]any) (map[string]any, error) {
|
||||
keySize := config["key_size"].(int)
|
||||
|
||||
// Logic:
|
||||
keyMaterial := make([]byte, keySize/8)
|
||||
|
||||
if _, err := rand.Read(keyMaterial); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := aes.NewCipher(keyMaterial); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Logic:
|
||||
generatedAt := time.Now().UTC().Format(time.RFC3339)
|
||||
|
||||
return map[string]any{
|
||||
"type": "symmetric",
|
||||
"algorithm": "aes",
|
||||
"key_size": keySize,
|
||||
"key_material": base64.StdEncoding.EncodeToString(keyMaterial),
|
||||
"generated_at": generatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyNormalizeSymmetricConfig
|
||||
// Function Purpose: Normalize symmetric configuration values.
|
||||
func obrimKeyNormalizeSymmetricConfig(config map[string]any) map[string]any {
|
||||
// Mutable Variable Purpose: Store normalized configuration.
|
||||
normalized := make(map[string]any)
|
||||
|
||||
normalized["algorithm"] = strings.ToLower(strings.TrimSpace(config["algorithm"].(string)))
|
||||
|
||||
switch value := config["key_size"].(type) {
|
||||
case int:
|
||||
normalized["key_size"] = value
|
||||
case int32:
|
||||
normalized["key_size"] = int(value)
|
||||
case int64:
|
||||
normalized["key_size"] = int(value)
|
||||
case float64:
|
||||
normalized["key_size"] = int(value)
|
||||
}
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyGenerateAsymmetric
|
||||
// Function Purpose: Generate asymmetric key material.
|
||||
func obrimKeyGenerateAsymmetric(config map[string]any) map[string]any {
|
||||
normalizedConfig := obrimKeyNormalizeAsymmetricConfig(config)
|
||||
|
||||
payload, err := obrimKeyGenerateECC(normalizedConfig)
|
||||
if err != nil {
|
||||
log.ObrimLog("ERROR", "ECC key generation failed.")
|
||||
return obrimKeyBuildError("FAILED_GENERATION")
|
||||
}
|
||||
|
||||
return map[string]any{
|
||||
"status": true,
|
||||
"code": "SUCCESS_KEY_GENERATED",
|
||||
"payload": obrimKeyBuildPayload(
|
||||
payload,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyGenerateECC
|
||||
// Function Purpose: Generate ECC key pair material.
|
||||
func obrimKeyGenerateECC(config map[string]any) (map[string]any, error) {
|
||||
_, _ = retriever.ObrimRetriever(
|
||||
"json",
|
||||
map[string]any{
|
||||
"resource": "application/metadata",
|
||||
"path": "application.lower",
|
||||
},
|
||||
)
|
||||
|
||||
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Logic:
|
||||
generatedAt := time.Now().UTC().Format(time.RFC3339)
|
||||
|
||||
return map[string]any{
|
||||
"type": "asymmetric",
|
||||
"algorithm": "ecc",
|
||||
"curve": "eddsa",
|
||||
"public_key": base64.StdEncoding.EncodeToString(publicKey),
|
||||
"private_key": base64.StdEncoding.EncodeToString(privateKey),
|
||||
"generated_at": generatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyNormalizeAsymmetricConfig
|
||||
// Function Purpose: Normalize asymmetric configuration values.
|
||||
func obrimKeyNormalizeAsymmetricConfig(config map[string]any) map[string]any {
|
||||
// Mutable Variable Purpose: Store normalized configuration.
|
||||
normalized := make(map[string]any)
|
||||
|
||||
normalized["algorithm"] = strings.ToLower(strings.TrimSpace(config["algorithm"].(string)))
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyBuildPayload
|
||||
// Function Purpose: Construct standardized success payloads.
|
||||
func obrimKeyBuildPayload(payload map[string]any) map[string]any {
|
||||
return payload
|
||||
}
|
||||
|
||||
// Function Name: obrimKeyBuildError
|
||||
// Function Purpose: Construct standardized error responses.
|
||||
func obrimKeyBuildError(code string) map[string]any {
|
||||
return map[string]any{
|
||||
"status": false,
|
||||
"code": code,
|
||||
"payload": nil,
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,207 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Log
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - Log
|
||||
|
|
||||
| Purpose:
|
||||
| - Provide a framework-level logging utility that records structured
|
||||
| plaintext log entries to a persistent filesystem location using a
|
||||
| deterministic and platform-aware storage strategy.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Use application metadata to resolve application identity.
|
||||
| - Persist UTF-8 plaintext log entries.
|
||||
| - Preserve existing log content.
|
||||
| - Use append-only write operations.
|
||||
| - Create required directories and files when missing.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimLog("service/create", "resource created")
|
||||
| - ObrimLog("helper/status", "status updated")
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package log
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go/module/name/essential/visible/service/helper/retriever"
|
||||
)
|
||||
|
||||
// Function Name: ObrimLog
|
||||
// Function Purpose: Write a structured log entry.
|
||||
func ObrimLog(label string, message string) {
|
||||
applicationName := ""
|
||||
|
||||
applicationValue := retriever.ObrimRetriever(
|
||||
"json",
|
||||
map[string]any{
|
||||
"resource": "application/metadata",
|
||||
"path": "application.lower",
|
||||
},
|
||||
)
|
||||
|
||||
if applicationValue != nil {
|
||||
applicationName = fmt.Sprint(applicationValue)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(applicationName) == "" {
|
||||
return
|
||||
}
|
||||
|
||||
timestamp := obrimLogTimestampGenerate()
|
||||
entry := obrimLogEntryBuild(timestamp, label, message)
|
||||
|
||||
logDirectoryPath := obrimLogDirectoryResolve(applicationName)
|
||||
if logDirectoryPath == "" {
|
||||
return
|
||||
}
|
||||
|
||||
logFilePath := obrimLogFileResolve(logDirectoryPath, applicationName)
|
||||
|
||||
if !obrimLogFileEnsure(logDirectoryPath, logFilePath) {
|
||||
return
|
||||
}
|
||||
|
||||
obrimLogWrite(logFilePath, entry)
|
||||
}
|
||||
|
||||
// Function Name: obrimLogTimestampGenerate
|
||||
// Function Purpose: Generate deterministic timestamps.
|
||||
func obrimLogTimestampGenerate() string {
|
||||
return time.Now().UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// Function Name: obrimLogEntryBuild
|
||||
// Function Purpose: Construct formatted log entries.
|
||||
func obrimLogEntryBuild(timestamp string, label string, message string) string {
|
||||
return fmt.Sprintf("[%s] [%s] %s\n", timestamp, label, message)
|
||||
}
|
||||
|
||||
// Function Name: obrimLogDirectoryResolve
|
||||
// Function Purpose: Resolve platform-specific log directory paths.
|
||||
func obrimLogDirectoryResolve(applicationName string) string {
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
xdgStateHome := strings.TrimSpace(os.Getenv("XDG_STATE_HOME"))
|
||||
|
||||
if xdgStateHome != "" {
|
||||
return filepath.Join(
|
||||
xdgStateHome,
|
||||
"."+applicationName,
|
||||
"logs",
|
||||
)
|
||||
}
|
||||
|
||||
homeDirectory, errorValue := os.UserHomeDir()
|
||||
if errorValue != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return filepath.Join(
|
||||
homeDirectory,
|
||||
".local",
|
||||
"state",
|
||||
"."+applicationName,
|
||||
"logs",
|
||||
)
|
||||
|
||||
case "windows":
|
||||
localApplicationData := strings.TrimSpace(os.Getenv("LOCALAPPDATA"))
|
||||
if localApplicationData == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
return filepath.Join(
|
||||
localApplicationData,
|
||||
applicationName,
|
||||
"Logs",
|
||||
)
|
||||
|
||||
case "darwin":
|
||||
homeDirectory, errorValue := os.UserHomeDir()
|
||||
if errorValue != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return filepath.Join(
|
||||
homeDirectory,
|
||||
"Library",
|
||||
"Logs",
|
||||
"."+applicationName,
|
||||
)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// Function Name: obrimLogFileResolve
|
||||
// Function Purpose: Resolve platform-specific log file paths.
|
||||
func obrimLogFileResolve(logDirectoryPath string, applicationName string) string {
|
||||
return filepath.Join(
|
||||
logDirectoryPath,
|
||||
applicationName+".log",
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimLogFileEnsure
|
||||
// Function Purpose: Create and verify required log directories and files.
|
||||
func obrimLogFileEnsure(logDirectoryPath string, logFilePath string) bool {
|
||||
if errorValue := os.MkdirAll(logDirectoryPath, 0755); errorValue != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
fileHandle, errorValue := os.OpenFile(
|
||||
logFilePath,
|
||||
os.O_CREATE,
|
||||
0644,
|
||||
)
|
||||
|
||||
if errorValue != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
defer fileHandle.Close()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Function Name: obrimLogWrite
|
||||
// Function Purpose: Persist log entries to the filesystem.
|
||||
func obrimLogWrite(logFilePath string, entry string) {
|
||||
fileHandle, errorValue := os.OpenFile(
|
||||
logFilePath,
|
||||
os.O_CREATE|os.O_APPEND|os.O_WRONLY,
|
||||
0644,
|
||||
)
|
||||
|
||||
if errorValue != nil {
|
||||
return
|
||||
}
|
||||
|
||||
defer fileHandle.Close()
|
||||
|
||||
// Logic: Persist the complete log entry as a single appended line.
|
||||
_, _ = fileHandle.WriteString(entry)
|
||||
}
|
||||
@ -0,0 +1,399 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Marker
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - Marker
|
||||
|
|
||||
| Purpose:
|
||||
| - Generate unique markers using time, random, and encoded strategies.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Validate marker type before execution.
|
||||
| - Maintain a consistent response structure.
|
||||
| - Isolate validation and generation workflows.
|
||||
| - Handle failures gracefully.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimMarker("time", config)
|
||||
| - ObrimMarker("random", config)
|
||||
| - ObrimMarker("encoded", config)
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
| - Scionite
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package marker
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go/module/name/essential/visible/service/helper/log"
|
||||
"go/module/name/essential/visible/service/helper/retriever"
|
||||
"go/module/name/essential/visible/service/helper/status"
|
||||
)
|
||||
|
||||
const (
|
||||
obrimMarkerTypeTime = "time"
|
||||
obrimMarkerTypeRandom = "random"
|
||||
obrimMarkerTypeEncoded = "encoded"
|
||||
)
|
||||
|
||||
type obrimMarkerResponse struct {
|
||||
Status bool `json:"status"`
|
||||
Code string `json:"code"`
|
||||
Payload any `json:"payload"`
|
||||
}
|
||||
|
||||
// Function Name: ObrimMarker
|
||||
// Function Purpose: Route marker generation requests and return a standardized marker response.
|
||||
func ObrimMarker(markerType string, config map[string]any) map[string]any {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
status.ObrimStatus("ERROR", "Marker execution failed.")
|
||||
log.ObrimLog("ERROR", "Marker execution panic recovered.")
|
||||
}
|
||||
}()
|
||||
|
||||
log.ObrimLog("INIT", "Marker utility initialized.")
|
||||
status.ObrimStatus("INFO", "Marker utility initialized.")
|
||||
|
||||
if err := obrimMarkerValidateType(markerType); err != nil {
|
||||
log.ObrimLog("ERROR", err.Error())
|
||||
return obrimMarkerBuildResponse(false, "FAILED_INVALID_TYPE", nil)
|
||||
}
|
||||
|
||||
return obrimMarkerRoute(markerType, config)
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerValidateType
|
||||
// Function Purpose: Validate supported marker generation types.
|
||||
func obrimMarkerValidateType(markerType string) error {
|
||||
switch markerType {
|
||||
case obrimMarkerTypeTime, obrimMarkerTypeRandom, obrimMarkerTypeEncoded:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unsupported marker type")
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerRoute
|
||||
// Function Purpose: Route execution to the selected marker generation workflow.
|
||||
func obrimMarkerRoute(markerType string, config map[string]any) map[string]any {
|
||||
switch markerType {
|
||||
case obrimMarkerTypeTime:
|
||||
return obrimMarkerTime(config)
|
||||
case obrimMarkerTypeRandom:
|
||||
return obrimMarkerRandom(config)
|
||||
case obrimMarkerTypeEncoded:
|
||||
return obrimMarkerEncoded(config)
|
||||
default:
|
||||
return obrimMarkerBuildResponse(false, "FAILED_INVALID_TYPE", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerBuildResponse
|
||||
// Function Purpose: Build standardized success and error responses.
|
||||
func obrimMarkerBuildResponse(statusValue bool, code string, payload any) map[string]any {
|
||||
return map[string]any{
|
||||
"status": statusValue,
|
||||
"code": code,
|
||||
"payload": payload,
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerTime
|
||||
// Function Purpose: Generate time-based unique markers.
|
||||
func obrimMarkerTime(config map[string]any) map[string]any {
|
||||
log.ObrimLog("VALIDATION", "Validating time marker configuration.")
|
||||
|
||||
epoch, instance, err := obrimMarkerValidateTime(config)
|
||||
if err != nil {
|
||||
log.ObrimLog("ERROR", err.Error())
|
||||
return obrimMarkerBuildResponse(false, "FAILED_VALIDATION", nil)
|
||||
}
|
||||
|
||||
log.ObrimLog("EXECUTION", "Generating time marker.")
|
||||
|
||||
markerValue := obrimMarkerTimeGenerate(epoch, instance)
|
||||
|
||||
payload := map[string]any{
|
||||
"marker": markerValue,
|
||||
"epoch": epoch,
|
||||
"instance": instance,
|
||||
}
|
||||
|
||||
status.ObrimStatus("SUCCESS", "Time marker generated.")
|
||||
log.ObrimLog("SUCCESS", "Time marker generated successfully.")
|
||||
|
||||
return obrimMarkerBuildResponse(true, "SUCCESS_TIME_MARKER_GENERATED", payload)
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerValidateTime
|
||||
// Function Purpose: Validate time marker configuration parameters.
|
||||
func obrimMarkerValidateTime(config map[string]any) (int64, string, error) {
|
||||
// Logic:
|
||||
var epochValue int64
|
||||
|
||||
// Logic:
|
||||
var instanceValue string
|
||||
|
||||
epochRaw, epochExists := config["epoch"]
|
||||
if !epochExists {
|
||||
return 0, "", fmt.Errorf("epoch is required")
|
||||
}
|
||||
|
||||
switch value := epochRaw.(type) {
|
||||
case int64:
|
||||
epochValue = value
|
||||
case int:
|
||||
epochValue = int64(value)
|
||||
case float64:
|
||||
epochValue = int64(value)
|
||||
default:
|
||||
return 0, "", fmt.Errorf("invalid epoch")
|
||||
}
|
||||
|
||||
if epochValue < 0 {
|
||||
return 0, "", fmt.Errorf("invalid epoch")
|
||||
}
|
||||
|
||||
instanceRaw, instanceExists := config["instance"]
|
||||
if !instanceExists {
|
||||
return 0, "", fmt.Errorf("instance is required")
|
||||
}
|
||||
|
||||
instanceValue, _ = instanceRaw.(string)
|
||||
|
||||
if strings.TrimSpace(instanceValue) == "" {
|
||||
return 0, "", fmt.Errorf("invalid instance")
|
||||
}
|
||||
|
||||
return epochValue, instanceValue, nil
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerTimeGenerate
|
||||
// Function Purpose: Produce the final time-based marker value.
|
||||
func obrimMarkerTimeGenerate(epoch int64, instance string) string {
|
||||
// Logic:
|
||||
var currentTime int64 = time.Now().UnixMilli()
|
||||
|
||||
return fmt.Sprintf("%d-%s", currentTime-epoch, instance)
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerRandom
|
||||
// Function Purpose: Generate random collision-resistant markers.
|
||||
func obrimMarkerRandom(config map[string]any) map[string]any {
|
||||
length, charset, err := obrimMarkerValidateRandom(config)
|
||||
if err != nil {
|
||||
log.ObrimLog("ERROR", err.Error())
|
||||
return obrimMarkerBuildResponse(false, "FAILED_VALIDATION", nil)
|
||||
}
|
||||
|
||||
markerValue, err := obrimMarkerRandomGenerate(length, charset)
|
||||
if err != nil {
|
||||
log.ObrimLog("ERROR", err.Error())
|
||||
return obrimMarkerBuildResponse(false, "FAILED_GENERATION", nil)
|
||||
}
|
||||
|
||||
payload := map[string]any{
|
||||
"marker": markerValue,
|
||||
"length": length,
|
||||
"charset": charset,
|
||||
}
|
||||
|
||||
status.ObrimStatus("SUCCESS", "Random marker generated.")
|
||||
log.ObrimLog("SUCCESS", "Random marker generated successfully.")
|
||||
|
||||
return obrimMarkerBuildResponse(true, "SUCCESS_RANDOM_MARKER_GENERATED", payload)
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerValidateRandom
|
||||
// Function Purpose: Validate random marker configuration parameters.
|
||||
func obrimMarkerValidateRandom(config map[string]any) (int, string, error) {
|
||||
// Logic:
|
||||
var lengthValue int
|
||||
|
||||
// Logic:
|
||||
var charsetValue string
|
||||
|
||||
lengthRaw, lengthExists := config["length"]
|
||||
if !lengthExists {
|
||||
return 0, "", fmt.Errorf("length is required")
|
||||
}
|
||||
|
||||
switch value := lengthRaw.(type) {
|
||||
case int:
|
||||
lengthValue = value
|
||||
case int64:
|
||||
lengthValue = int(value)
|
||||
case float64:
|
||||
lengthValue = int(value)
|
||||
default:
|
||||
return 0, "", fmt.Errorf("invalid length")
|
||||
}
|
||||
|
||||
if lengthValue <= 0 {
|
||||
return 0, "", fmt.Errorf("invalid length")
|
||||
}
|
||||
|
||||
charsetRaw, charsetExists := config["charset"]
|
||||
if !charsetExists {
|
||||
return 0, "", fmt.Errorf("charset is required")
|
||||
}
|
||||
|
||||
charsetValue, _ = charsetRaw.(string)
|
||||
|
||||
if charsetValue == "" {
|
||||
return 0, "", fmt.Errorf("invalid charset")
|
||||
}
|
||||
|
||||
return lengthValue, charsetValue, nil
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerRandomGenerate
|
||||
// Function Purpose: Produce the final random marker value.
|
||||
func obrimMarkerRandomGenerate(length int, charset string) (string, error) {
|
||||
// Logic:
|
||||
var builder strings.Builder
|
||||
|
||||
for i := 0; i < length; i++ {
|
||||
index, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
builder.WriteByte(charset[index.Int64()])
|
||||
}
|
||||
|
||||
return builder.String(), nil
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerEncoded
|
||||
// Function Purpose: Generate deterministic encoded markers.
|
||||
func obrimMarkerEncoded(config map[string]any) map[string]any {
|
||||
data, length, charset, salt, err := obrimMarkerValidateEncoded(config)
|
||||
if err != nil {
|
||||
log.ObrimLog("ERROR", err.Error())
|
||||
return obrimMarkerBuildResponse(false, "FAILED_VALIDATION", nil)
|
||||
}
|
||||
|
||||
markerValue := obrimMarkerEncodedGenerate(data, length, charset, salt)
|
||||
|
||||
payload := map[string]any{
|
||||
"marker": markerValue,
|
||||
"source": data,
|
||||
"length": length,
|
||||
}
|
||||
|
||||
status.ObrimStatus("SUCCESS", "Encoded marker generated.")
|
||||
log.ObrimLog("SUCCESS", "Encoded marker generated successfully.")
|
||||
|
||||
return obrimMarkerBuildResponse(true, "SUCCESS_ENCODED_MARKER_GENERATED", payload)
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerValidateEncoded
|
||||
// Function Purpose: Validate encoded marker configuration parameters.
|
||||
func obrimMarkerValidateEncoded(config map[string]any) (string, int, string, string, error) {
|
||||
// Logic:
|
||||
var dataValue string
|
||||
|
||||
// Logic:
|
||||
var lengthValue int
|
||||
|
||||
// Logic:
|
||||
var charsetValue string
|
||||
|
||||
// Logic:
|
||||
var saltValue string
|
||||
|
||||
dataRaw, dataExists := config["data"]
|
||||
if !dataExists {
|
||||
return "", 0, "", "", fmt.Errorf("data is required")
|
||||
}
|
||||
|
||||
dataValue, _ = dataRaw.(string)
|
||||
|
||||
if dataValue == "" {
|
||||
return "", 0, "", "", fmt.Errorf("invalid data")
|
||||
}
|
||||
|
||||
lengthRaw, lengthExists := config["length"]
|
||||
if !lengthExists {
|
||||
return "", 0, "", "", fmt.Errorf("length is required")
|
||||
}
|
||||
|
||||
switch value := lengthRaw.(type) {
|
||||
case int:
|
||||
lengthValue = value
|
||||
case int64:
|
||||
lengthValue = int(value)
|
||||
case float64:
|
||||
lengthValue = int(value)
|
||||
default:
|
||||
return "", 0, "", "", fmt.Errorf("invalid length")
|
||||
}
|
||||
|
||||
if lengthValue <= 0 {
|
||||
return "", 0, "", "", fmt.Errorf("invalid length")
|
||||
}
|
||||
|
||||
charsetRaw, charsetExists := config["charset"]
|
||||
if !charsetExists {
|
||||
return "", 0, "", "", fmt.Errorf("charset is required")
|
||||
}
|
||||
|
||||
charsetValue, _ = charsetRaw.(string)
|
||||
|
||||
if charsetValue == "" {
|
||||
return "", 0, "", "", fmt.Errorf("invalid charset")
|
||||
}
|
||||
|
||||
if saltRaw, saltExists := config["salt"]; saltExists {
|
||||
saltValue, _ = saltRaw.(string)
|
||||
}
|
||||
|
||||
return dataValue, lengthValue, charsetValue, saltValue, nil
|
||||
}
|
||||
|
||||
// Function Name: obrimMarkerEncodedGenerate
|
||||
// Function Purpose: Produce the final encoded marker value.
|
||||
func obrimMarkerEncodedGenerate(data string, length int, charset string, salt string) string {
|
||||
// Logic:
|
||||
var hashValue [32]byte = sha256.Sum256([]byte(data + salt))
|
||||
|
||||
// Logic:
|
||||
var encoded string = hex.EncodeToString(hashValue[:])
|
||||
|
||||
// Logic:
|
||||
var builder strings.Builder
|
||||
|
||||
for i := 0; i < length; i++ {
|
||||
index := int(encoded[i%len(encoded)]) % len(charset)
|
||||
builder.WriteByte(charset[index])
|
||||
}
|
||||
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
var (
|
||||
_ = retriever.ObrimRetriever
|
||||
)
|
||||
@ -0,0 +1,363 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Progress
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - Progress
|
||||
|
|
||||
| Purpose:
|
||||
| - Manage lifecycle-aware countable and uncountable progress tracking.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Validate all inputs before processing.
|
||||
| - Support countable and uncountable progress workflows.
|
||||
| - Generate standardized responses.
|
||||
| - Generate CLI-friendly progress messages and visuals.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimProgress("countable", config)
|
||||
| - ObrimProgress("uncountable", config)
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
| - Scionite
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package progress
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"go/module/name/essential/external/service/helper/log"
|
||||
"go/module/name/essential/external/service/helper/retriever"
|
||||
"go/module/name/essential/external/service/helper/status"
|
||||
)
|
||||
|
||||
var (
|
||||
// Variable Purpose: Protect progress state transitions from concurrent corruption.
|
||||
obrimProgressMutex sync.Mutex
|
||||
)
|
||||
|
||||
type obrimProgressResponse struct {
|
||||
Status bool `json:"status"`
|
||||
Code string `json:"code"`
|
||||
Payload map[string]any `json:"payload"`
|
||||
}
|
||||
|
||||
// Function Name: ObrimProgress
|
||||
// Function Purpose: Manage lifecycle-aware countable and uncountable progress tracking operations.
|
||||
func ObrimProgress(progressType string, config map[string]any) map[string]any {
|
||||
obrimProgressMutex.Lock()
|
||||
defer obrimProgressMutex.Unlock()
|
||||
|
||||
_, _ = retriever.ObrimRetriever(
|
||||
"json",
|
||||
map[string]any{
|
||||
"resource": "application/metadata",
|
||||
"path": "application.lower",
|
||||
},
|
||||
)
|
||||
|
||||
if !obrimProgressValidate(progressType, config) {
|
||||
status.ObrimStatus("ERROR", "Progress configuration is invalid.")
|
||||
log.ObrimLog("ERROR", "FAILED_PROGRESS_MISCONFIGURED")
|
||||
|
||||
return obrimProgressBuildResponse(
|
||||
false,
|
||||
"FAILED_PROGRESS_MISCONFIGURED",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
// Variable Purpose: Current lifecycle state.
|
||||
state := fmt.Sprintf("%v", config["state"])
|
||||
|
||||
if !obrimProgressHandleState(state) {
|
||||
status.ObrimStatus("ERROR", "Invalid lifecycle state.")
|
||||
log.ObrimLog("ERROR", "FAILED_PROGRESS_MISCONFIGURED")
|
||||
|
||||
return obrimProgressBuildResponse(
|
||||
false,
|
||||
"FAILED_PROGRESS_MISCONFIGURED",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
switch progressType {
|
||||
case "countable":
|
||||
return obrimProgressCountable(config)
|
||||
|
||||
case "uncountable":
|
||||
return obrimProgressUncountable(config)
|
||||
|
||||
default:
|
||||
status.ObrimStatus("ERROR", "Unsupported progress type.")
|
||||
log.ObrimLog("ERROR", "FAILED_PROGRESS_MISCONFIGURED")
|
||||
|
||||
return obrimProgressBuildResponse(
|
||||
false,
|
||||
"FAILED_PROGRESS_MISCONFIGURED",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimProgressValidate
|
||||
// Function Purpose: Validate input parameters and configuration consistency.
|
||||
func obrimProgressValidate(progressType string, config map[string]any) bool {
|
||||
if config == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Variable Purpose: Lifecycle state.
|
||||
stateValue, stateExists := config["state"]
|
||||
if !stateExists {
|
||||
return false
|
||||
}
|
||||
|
||||
state := fmt.Sprintf("%v", stateValue)
|
||||
|
||||
switch state {
|
||||
case "started", "running", "completed", "canceled":
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
switch progressType {
|
||||
case "countable":
|
||||
currentValue, currentExists := config["current"]
|
||||
targetValue, targetExists := config["target"]
|
||||
|
||||
if !currentExists || !targetExists {
|
||||
return false
|
||||
}
|
||||
|
||||
current, currentOK := currentValue.(int)
|
||||
target, targetOK := targetValue.(int)
|
||||
|
||||
if !currentOK || !targetOK {
|
||||
return false
|
||||
}
|
||||
|
||||
if target <= 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
_ = current
|
||||
|
||||
case "uncountable":
|
||||
placeholderValue, placeholderExists := config["placeholder"]
|
||||
|
||||
if !placeholderExists {
|
||||
return false
|
||||
}
|
||||
|
||||
placeholder := fmt.Sprintf("%v", placeholderValue)
|
||||
|
||||
if strings.TrimSpace(placeholder) == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Function Name: obrimProgressHandleState
|
||||
// Function Purpose: Process lifecycle state transitions.
|
||||
func obrimProgressHandleState(state string) bool {
|
||||
switch state {
|
||||
case "started":
|
||||
log.ObrimLog("INIT", "Progress tracking started.")
|
||||
status.ObrimStatus("INFO", "Progress tracking started.")
|
||||
|
||||
case "running":
|
||||
log.ObrimLog("SYNC", "Progress tracking updated.")
|
||||
status.ObrimStatus("INFO", "Progress tracking running.")
|
||||
|
||||
case "completed":
|
||||
log.ObrimLog("SUCCESS", "Progress tracking completed.")
|
||||
status.ObrimStatus("SUCCESS", "Progress tracking completed.")
|
||||
|
||||
case "canceled":
|
||||
log.ObrimLog("ERROR", "Progress tracking canceled.")
|
||||
status.ObrimStatus("WARNING", "Progress tracking canceled.")
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Function Name: obrimProgressGenerateMessage
|
||||
// Function Purpose: Generate human-readable progress messages.
|
||||
func obrimProgressGenerateMessage(progressType string, data map[string]any) string {
|
||||
if progressType == "countable" {
|
||||
return fmt.Sprintf(
|
||||
"Progress %d%% complete.",
|
||||
data["percentage"].(int),
|
||||
)
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"Activity in progress: %s",
|
||||
data["placeholder"].(string),
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimProgressGenerateVisual
|
||||
// Function Purpose: Generate CLI-friendly visual progress representations.
|
||||
func obrimProgressGenerateVisual(progressType string, data map[string]any) string {
|
||||
if progressType == "countable" {
|
||||
// Variable Purpose: Percentage value.
|
||||
percentage := data["percentage"].(int)
|
||||
|
||||
// Variable Purpose: Total bar width.
|
||||
barWidth := 20
|
||||
|
||||
// Variable Purpose: Filled segments.
|
||||
filled := int(math.Round(float64(percentage) / 100 * float64(barWidth)))
|
||||
|
||||
if filled > barWidth {
|
||||
filled = barWidth
|
||||
}
|
||||
|
||||
if filled < 0 {
|
||||
filled = 0
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"[%s%s] %d%%",
|
||||
strings.Repeat("#", filled),
|
||||
strings.Repeat("-", barWidth-filled),
|
||||
percentage,
|
||||
)
|
||||
}
|
||||
|
||||
return "[....................]"
|
||||
}
|
||||
|
||||
// Function Name: obrimProgressBuildResponse
|
||||
// Function Purpose: Construct standardized utility response payloads.
|
||||
func obrimProgressBuildResponse(
|
||||
statusValue bool,
|
||||
code string,
|
||||
payload map[string]any,
|
||||
) map[string]any {
|
||||
return map[string]any{
|
||||
"status": statusValue,
|
||||
"code": code,
|
||||
"payload": payload,
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimProgressCountable
|
||||
// Function Purpose: Process countable progress tracking workflows.
|
||||
func obrimProgressCountable(config map[string]any) map[string]any {
|
||||
// Variable Purpose: Current lifecycle state.
|
||||
state := config["state"].(string)
|
||||
|
||||
// Variable Purpose: Current progress value.
|
||||
current := config["current"].(int)
|
||||
|
||||
// Variable Purpose: Target progress value.
|
||||
target := config["target"].(int)
|
||||
|
||||
// Variable Purpose: Calculated percentage.
|
||||
percentage := obrimProgressCalculatePercentage(current, target)
|
||||
|
||||
// Variable Purpose: Payload object.
|
||||
payload := map[string]any{
|
||||
"state": state,
|
||||
"current": current,
|
||||
"target": target,
|
||||
"percentage": percentage,
|
||||
}
|
||||
|
||||
payload["message"] = obrimProgressGenerateMessage("countable", payload)
|
||||
payload["visual"] = obrimProgressGenerateVisual("countable", payload)
|
||||
|
||||
return obrimProgressBuildResponse(
|
||||
true,
|
||||
"SUCCESS_PROGRESS_COUNTABLE",
|
||||
payload,
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimProgressCalculatePercentage
|
||||
// Function Purpose: Calculate and normalize completion percentages.
|
||||
func obrimProgressCalculatePercentage(current int, target int) int {
|
||||
if current < 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
if target <= 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
percentage := int(
|
||||
math.Round(
|
||||
(float64(current) / float64(target)) * 100,
|
||||
),
|
||||
)
|
||||
|
||||
if percentage > 100 {
|
||||
return 100
|
||||
}
|
||||
|
||||
if percentage < 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return percentage
|
||||
}
|
||||
|
||||
// Function Name: obrimProgressUncountable
|
||||
// Function Purpose: Process uncountable progress tracking workflows.
|
||||
func obrimProgressUncountable(config map[string]any) map[string]any {
|
||||
// Variable Purpose: Current lifecycle state.
|
||||
state := config["state"].(string)
|
||||
|
||||
// Variable Purpose: Placeholder activity message.
|
||||
placeholder := obrimProgressResolvePlaceholder(
|
||||
fmt.Sprintf("%v", config["placeholder"]),
|
||||
)
|
||||
|
||||
// Variable Purpose: Payload object.
|
||||
payload := map[string]any{
|
||||
"state": state,
|
||||
"placeholder": placeholder,
|
||||
}
|
||||
|
||||
payload["message"] = obrimProgressGenerateMessage("uncountable", payload)
|
||||
payload["visual"] = obrimProgressGenerateVisual("uncountable", payload)
|
||||
|
||||
return obrimProgressBuildResponse(
|
||||
true,
|
||||
"SUCCESS_PROGRESS_UNCOUNTABLE",
|
||||
payload,
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimProgressResolvePlaceholder
|
||||
// Function Purpose: Validate and prepare placeholder activity messages.
|
||||
func obrimProgressResolvePlaceholder(placeholder string) string {
|
||||
return strings.TrimSpace(placeholder)
|
||||
}
|
||||
@ -0,0 +1,422 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Retriever
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - Retriever
|
||||
|
|
||||
| Purpose:
|
||||
| - Retrieve data from supported resource providers through a unified
|
||||
| retrieval interface.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Validate retrieval type before processing.
|
||||
| - Validate configuration according to retrieval type.
|
||||
| - Route retrieval through type-based dispatching.
|
||||
| - Maintain provider registries per retrieval type.
|
||||
| - Hide provider-specific implementation details from consumers.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimRetriever("json", config)
|
||||
| - ObrimRetrieverJsonRegister("metadata", provider)
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
| - Scionite
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package retriever
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"go/module/name/essential/external/service/helper/log"
|
||||
"go/module/name/essential/external/service/helper/status"
|
||||
)
|
||||
|
||||
// JSON Provider Purpose: Retrieve a complete resource payload.
|
||||
type ObrimRetrieverJsonProvider interface {
|
||||
Retrieve() (any, error)
|
||||
}
|
||||
|
||||
// JSON Registry Purpose: Store registered JSON providers.
|
||||
var ObrimRetrieverJsonRegistry = struct {
|
||||
sync.RWMutex
|
||||
Providers map[string]ObrimRetrieverJsonProvider
|
||||
}{
|
||||
Providers: map[string]ObrimRetrieverJsonProvider{},
|
||||
}
|
||||
|
||||
// DB Registry Purpose: Store registered database providers.
|
||||
var ObrimRetrieverDbRegistry = struct {
|
||||
sync.RWMutex
|
||||
Providers map[string]any
|
||||
}{
|
||||
Providers: map[string]any{},
|
||||
}
|
||||
|
||||
// Function Name: ObrimRetriever
|
||||
// Function Purpose: Retrieve data using a unified retrieval interface.
|
||||
func ObrimRetriever(retrievalType string, config map[string]any) map[string]any {
|
||||
status.ObrimStatus("INFO", "Processing retrieval request.")
|
||||
log.ObrimLog("INIT", "Retriever execution started.")
|
||||
|
||||
if response := obrimRetrieverValidateType(retrievalType); response != nil {
|
||||
return response
|
||||
}
|
||||
|
||||
if response := obrimRetrieverValidateConfig(retrievalType, config); response != nil {
|
||||
return response
|
||||
}
|
||||
|
||||
switch retrievalType {
|
||||
case "json":
|
||||
return obrimRetrieverJson(config)
|
||||
|
||||
case "db":
|
||||
return obrimRetrieverDb(config)
|
||||
|
||||
default:
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_UNSUPPORTED_TYPE",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: ObrimRetrieverJsonRegister
|
||||
// Function Purpose: Register a JSON provider against a resource identifier.
|
||||
func ObrimRetrieverJsonRegister(resource string, provider any) {
|
||||
jsonProvider, ok := provider.(ObrimRetrieverJsonProvider)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
ObrimRetrieverJsonRegistry.Lock()
|
||||
defer ObrimRetrieverJsonRegistry.Unlock()
|
||||
|
||||
ObrimRetrieverJsonRegistry.Providers[resource] = jsonProvider
|
||||
}
|
||||
|
||||
// Function Name: ObrimRetrieverDbRegister
|
||||
// Function Purpose: Register a database provider against a resource identifier.
|
||||
func ObrimRetrieverDbRegister(resource string, provider any) {
|
||||
ObrimRetrieverDbRegistry.Lock()
|
||||
defer ObrimRetrieverDbRegistry.Unlock()
|
||||
|
||||
ObrimRetrieverDbRegistry.Providers[resource] = provider
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverValidateType
|
||||
// Function Purpose: Validate the requested retrieval type.
|
||||
func obrimRetrieverValidateType(retrievalType string) map[string]any {
|
||||
switch retrievalType {
|
||||
case "json", "db":
|
||||
return nil
|
||||
default:
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_UNSUPPORTED_TYPE",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverValidateConfig
|
||||
// Function Purpose: Validate configuration according to retrieval type requirements.
|
||||
func obrimRetrieverValidateConfig(
|
||||
retrievalType string,
|
||||
config map[string]any,
|
||||
) map[string]any {
|
||||
if config == nil {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_MISSING_CONFIGURATION",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
switch retrievalType {
|
||||
case "json":
|
||||
return obrimRetrieverJsonValidate(config)
|
||||
|
||||
case "db":
|
||||
return obrimRetrieverDbValidate(config)
|
||||
|
||||
default:
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_UNSUPPORTED_TYPE",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverResolveProvider
|
||||
// Function Purpose: Resolve a provider using a registered resource identifier.
|
||||
func obrimRetrieverResolveProvider(resource string) (any, bool) {
|
||||
ObrimRetrieverJsonRegistry.RLock()
|
||||
defer ObrimRetrieverJsonRegistry.RUnlock()
|
||||
|
||||
provider, exists := ObrimRetrieverJsonRegistry.Providers[resource]
|
||||
|
||||
return provider, exists
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverBuildResponse
|
||||
// Function Purpose: Build standardized utility responses.
|
||||
func obrimRetrieverBuildResponse(
|
||||
statusValue bool,
|
||||
code string,
|
||||
payload any,
|
||||
) map[string]any {
|
||||
return map[string]any{
|
||||
"status": statusValue,
|
||||
"code": code,
|
||||
"payload": payload,
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverJson
|
||||
// Function Purpose: Process JSON retrieval requests.
|
||||
func obrimRetrieverJson(config map[string]any) map[string]any {
|
||||
resource := config["resource"].(string)
|
||||
|
||||
provider, exists := obrimRetrieverResolveProvider(resource)
|
||||
if !exists {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_RESOURCE_NOT_FOUND",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
jsonProvider := provider.(ObrimRetrieverJsonProvider)
|
||||
|
||||
if _, exists := config["path"]; exists {
|
||||
return obrimRetrieverJsonPath(jsonProvider, config)
|
||||
}
|
||||
|
||||
if _, exists := config["fields"]; exists {
|
||||
return obrimRetrieverJsonFields(jsonProvider, config)
|
||||
}
|
||||
|
||||
return obrimRetrieverJsonResource(jsonProvider)
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverJsonResource
|
||||
// Function Purpose: Retrieve a complete JSON resource payload.
|
||||
func obrimRetrieverJsonResource(
|
||||
provider ObrimRetrieverJsonProvider,
|
||||
) map[string]any {
|
||||
data, err := provider.Retrieve()
|
||||
if err != nil {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_RESOURCE_NOT_FOUND",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
return obrimRetrieverBuildResponse(
|
||||
true,
|
||||
"SUCCESS_RESOURCE",
|
||||
map[string]any{
|
||||
"data": data,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverJsonPath
|
||||
// Function Purpose: Retrieve a value using a dot-notation path.
|
||||
func obrimRetrieverJsonPath(
|
||||
provider ObrimRetrieverJsonProvider,
|
||||
config map[string]any,
|
||||
) map[string]any {
|
||||
data, err := provider.Retrieve()
|
||||
if err != nil {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_RESOURCE_NOT_FOUND",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
path := config["path"].(string)
|
||||
|
||||
value, found := obrimRetrieverJsonResolvePath(data, path)
|
||||
if !found {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_PATH_NOT_FOUND",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
return obrimRetrieverBuildResponse(
|
||||
true,
|
||||
"SUCCESS_PATH",
|
||||
map[string]any{
|
||||
"data": value,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverJsonFields
|
||||
// Function Purpose: Retrieve multiple values using field path selection.
|
||||
func obrimRetrieverJsonFields(
|
||||
provider ObrimRetrieverJsonProvider,
|
||||
config map[string]any,
|
||||
) map[string]any {
|
||||
data, err := provider.Retrieve()
|
||||
if err != nil {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_RESOURCE_NOT_FOUND",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
fields, ok := config["fields"].([]string)
|
||||
if !ok {
|
||||
interfaceFields, ok := config["fields"].([]any)
|
||||
if !ok {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_INVALID_CONFIGURATION",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
fields = make([]string, 0, len(interfaceFields))
|
||||
|
||||
for _, field := range interfaceFields {
|
||||
fieldString, ok := field.(string)
|
||||
if !ok {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_INVALID_CONFIGURATION",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
fields = append(fields, fieldString)
|
||||
}
|
||||
}
|
||||
|
||||
result := map[string]any{}
|
||||
|
||||
for _, field := range fields {
|
||||
value, found := obrimRetrieverJsonResolvePath(data, field)
|
||||
if !found {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_FIELD_NOT_FOUND",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
result[field] = value
|
||||
}
|
||||
|
||||
return obrimRetrieverBuildResponse(
|
||||
true,
|
||||
"SUCCESS_FIELDS",
|
||||
map[string]any{
|
||||
"data": result,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverJsonValidate
|
||||
// Function Purpose: Validate JSON retrieval configuration.
|
||||
func obrimRetrieverJsonValidate(config map[string]any) map[string]any {
|
||||
resource, exists := config["resource"]
|
||||
if !exists {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_MISSING_CONFIGURATION",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
resourceString, ok := resource.(string)
|
||||
if !ok || strings.TrimSpace(resourceString) == "" {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_INVALID_CONFIGURATION",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
_, hasPath := config["path"]
|
||||
_, hasFields := config["fields"]
|
||||
|
||||
if hasPath && hasFields {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_INVALID_CONFIGURATION",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverDb
|
||||
// Function Purpose: Process database retrieval requests.
|
||||
func obrimRetrieverDb(config map[string]any) map[string]any {
|
||||
return obrimRetrieverBuildResponse(
|
||||
false,
|
||||
"FAILED_NOT_IMPLEMENTED",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverDbValidate
|
||||
// Function Purpose: Validate database retrieval configuration.
|
||||
func obrimRetrieverDbValidate(config map[string]any) map[string]any {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Function Name: obrimRetrieverJsonResolvePath
|
||||
// Function Purpose: Resolve a dot-notation path from a resource payload.
|
||||
func obrimRetrieverJsonResolvePath(
|
||||
data any,
|
||||
path string,
|
||||
) (any, bool) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return data, true
|
||||
}
|
||||
|
||||
current := data
|
||||
|
||||
for _, segment := range strings.Split(path, ".") {
|
||||
object, ok := current.(map[string]any)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
value, exists := object[segment]
|
||||
if !exists {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
current = value
|
||||
}
|
||||
|
||||
return current, true
|
||||
}
|
||||
@ -0,0 +1,119 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Status
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name:
|
||||
| - Status
|
||||
|
|
||||
| Purpose:
|
||||
| - Provide a framework-level CLI status utility that standardizes
|
||||
| terminal message presentation using semantic labels and visual
|
||||
| indicators to ensure consistent output across all applications.
|
||||
|
|
||||
| Guidelines:
|
||||
| - Accept semantic label and message as input.
|
||||
| - Normalize and validate labels.
|
||||
| - Default unsupported, empty, or invalid labels to INFO.
|
||||
| - Emit exactly one terminal message per invocation.
|
||||
|
|
||||
| Examples:
|
||||
| - ObrimStatus("INFO", "Application started.")
|
||||
| - ObrimStatus("SUCCESS", "Operation completed.")
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Contributor:
|
||||
| - Rajon Ahmed
|
||||
|
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
package status
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Function Name: ObrimStatus
|
||||
// Function Purpose: Emit a standardized CLI status message.
|
||||
func ObrimStatus(label string, message string) {
|
||||
// Logic:
|
||||
var normalizedLabel string = obrimStatusNormalizeLabel(label)
|
||||
|
||||
// Logic:
|
||||
var formattedLabel string = obrimStatusFormatLabel(normalizedLabel)
|
||||
|
||||
// Logic:
|
||||
var indicator string = obrimStatusFormatIndicator(normalizedLabel)
|
||||
|
||||
// Logic:
|
||||
var finalMessage string = obrimStatusBuildMessage(
|
||||
formattedLabel,
|
||||
indicator,
|
||||
message,
|
||||
)
|
||||
|
||||
// Logic:
|
||||
fmt.Println(finalMessage)
|
||||
}
|
||||
|
||||
// Function Name: obrimStatusNormalizeLabel
|
||||
// Function Purpose: Normalize and validate labels.
|
||||
func obrimStatusNormalizeLabel(label string) string {
|
||||
// Logic:
|
||||
var normalizedLabel string = strings.ToUpper(strings.TrimSpace(label))
|
||||
|
||||
switch normalizedLabel {
|
||||
case "INFO":
|
||||
return "INFO"
|
||||
case "WARNING":
|
||||
return "WARNING"
|
||||
case "SUCCESS":
|
||||
return "SUCCESS"
|
||||
case "ERROR":
|
||||
return "ERROR"
|
||||
default:
|
||||
return "INFO"
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimStatusFormatLabel
|
||||
// Function Purpose: Format semantic labels.
|
||||
func obrimStatusFormatLabel(label string) string {
|
||||
return "[" + label + "]"
|
||||
}
|
||||
|
||||
// Function Name: obrimStatusFormatIndicator
|
||||
// Function Purpose: Generate visual status indicators.
|
||||
func obrimStatusFormatIndicator(label string) string {
|
||||
switch label {
|
||||
case "INFO":
|
||||
return "ℹ"
|
||||
case "WARNING":
|
||||
return "⚠"
|
||||
case "SUCCESS":
|
||||
return "✓"
|
||||
case "ERROR":
|
||||
return "✗"
|
||||
default:
|
||||
return "ℹ"
|
||||
}
|
||||
}
|
||||
|
||||
// Function Name: obrimStatusBuildMessage
|
||||
// Function Purpose: Construct the final terminal message.
|
||||
func obrimStatusBuildMessage(
|
||||
label string,
|
||||
indicator string,
|
||||
message string,
|
||||
) string {
|
||||
return fmt.Sprintf("%s %s %s", indicator, label, message)
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user