Class: Calvery::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/calvery.rb

Instance Method Summary collapse

Constructor Details

#initialize(token, team, **options) ⇒ Client

Returns a new instance of Client.

Parameters:

  • token (String)

    Personal access token (cvsm_…)

  • team (String)

    Team slug or UUID

  • options (Hash)

    :base_url, :environment, :cache_ttl, :max_retries, :timeout

Raises:



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/calvery.rb', line 42

def initialize(token, team, **options)
  raise ConfigError, "token wajib" if token.nil? || token.empty?
  raise ConfigError, "team wajib (slug atau UUID)" if team.nil? || team.empty?

  @token       = token
  @team_input  = team
  @base_url    = (options[:base_url]    || DEFAULT_BASE_URL).sub(%r{/+\z}, "")
  @default_env = options[:environment]  || DEFAULT_ENVIRONMENT
  @cache_ttl   = options[:cache_ttl]    || DEFAULT_CACHE_TTL
  @max_retries = options[:max_retries]  || DEFAULT_MAX_RETRIES
  @timeout     = options[:timeout]      || DEFAULT_TIMEOUT

  @resolved_team_id = nil
  @cache = {}
  @mutex = Mutex.new
end

Instance Method Details

#clear_cacheObject



104
105
106
# File 'lib/calvery.rb', line 104

def clear_cache
  @mutex.synchronize { @cache.clear }
end

#get(name, environment: nil) ⇒ Object

Ambil satu secret by name (default env).

Raises:



60
61
62
63
64
65
# File 'lib/calvery.rb', line 60

def get(name, environment: nil)
  env = environment || @default_env
  all = get_all(environment: env)
  raise NotFound, %(secret "#{name}" tidak ditemukan di environment "#{env}") unless all.key?(name)
  all[name]
end

#get_all(environment: nil) ⇒ Object

Ambil semua secret untuk environment tertentu sebagai Hash.

Raises:



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/calvery.rb', line 68

def get_all(environment: nil)
  env = environment || @default_env
  @mutex.synchronize do
    entry = @cache[env]
    return entry[:data].dup if entry && entry[:expires_at] > Time.now.to_i
  end

  team_id = resolve_team_id
  query   = URI.encode_www_form(format: "json", environment: env)
  url     = "#{@base_url}/api/v1/teams/#{team_id}/secrets/export?#{query}"
  body    = do_with_retry(:get, url)
  data    = parse_json(body)
  raise DecodeError, "response bukan object JSON" unless data.is_a?(Hash)

  if @cache_ttl.positive?
    @mutex.synchronize do
      @cache[env] = { data: data.dup, expires_at: Time.now.to_i + @cache_ttl }
    end
  end
  data
end

#inject!(overwrite: false, environment: nil) ⇒ Object

Populate ENV dari semua secret. Return array nama yang di-inject.



91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/calvery.rb', line 91

def inject!(overwrite: false, environment: nil)
  secrets  = get_all(environment: environment)
  injected = []
  secrets.each do |k, v|
    if !overwrite && !ENV[k].to_s.empty?
      next
    end
    ENV[k] = v
    injected << k
  end
  injected
end