|
| 1 | +require "flipper/adapters/http/client" |
| 2 | +require "flipper/typecast" |
| 3 | + |
| 4 | +module Flipper |
| 5 | + module Cloud |
| 6 | + MigrateResult = Struct.new(:code, :url, :message, keyword_init: true) |
| 7 | + |
| 8 | + DEFAULT_CLOUD_URL = "https://www.flippercloud.io".freeze |
| 9 | + |
| 10 | + # Public: Migrate features to Flipper Cloud. |
| 11 | + # |
| 12 | + # flipper - The Flipper instance to export features from (default: Flipper). |
| 13 | + # app_name - Optional String name of the application. |
| 14 | + # |
| 15 | + # Returns a MigrateResult with code, url, and message. |
| 16 | + def self.migrate(flipper = Flipper, app_name: nil) |
| 17 | + export = flipper.export(format: :json, version: 1) |
| 18 | + payload = { |
| 19 | + export: Typecast.from_json(export.contents), |
| 20 | + metadata: {app_name: app_name}, |
| 21 | + } |
| 22 | + |
| 23 | + client = build_client("/api") |
| 24 | + response = client.post("/migrate", Typecast.to_gzip(Typecast.to_json(payload))) |
| 25 | + body = Typecast.from_json(response.body) rescue nil |
| 26 | + |
| 27 | + MigrateResult.new( |
| 28 | + code: response.code.to_i, |
| 29 | + url: body&.dig("url"), |
| 30 | + message: body&.dig("error"), |
| 31 | + ) |
| 32 | + end |
| 33 | + |
| 34 | + # Public: Push features to an existing Flipper Cloud project. |
| 35 | + # |
| 36 | + # token - The String token for the Cloud environment. |
| 37 | + # flipper - The Flipper instance to export features from (default: Flipper). |
| 38 | + # |
| 39 | + # Returns a MigrateResult with code and message. |
| 40 | + def self.push(token, flipper = Flipper) |
| 41 | + export = flipper.export(format: :json, version: 1) |
| 42 | + |
| 43 | + client = build_client("/adapter", headers: { |
| 44 | + "flipper-cloud-token" => token, |
| 45 | + }) |
| 46 | + response = client.post("/import", Typecast.to_gzip(export.contents)) |
| 47 | + body = Typecast.from_json(response.body) rescue nil |
| 48 | + |
| 49 | + MigrateResult.new( |
| 50 | + code: response.code.to_i, |
| 51 | + url: nil, |
| 52 | + message: body&.dig("error"), |
| 53 | + ) |
| 54 | + end |
| 55 | + |
| 56 | + # Private: Build an HTTP client for Cloud API requests. |
| 57 | + def self.build_client(path, headers: {}) |
| 58 | + base_url = ENV.fetch("FLIPPER_CLOUD_URL", DEFAULT_CLOUD_URL) |
| 59 | + |
| 60 | + Flipper::Adapters::Http::Client.new( |
| 61 | + url: "#{base_url}#{path}", |
| 62 | + headers: {"content-encoding" => "gzip"}.merge(headers), |
| 63 | + open_timeout: 5, |
| 64 | + read_timeout: 30, |
| 65 | + write_timeout: 30, |
| 66 | + max_retries: 2, |
| 67 | + ) |
| 68 | + end |
| 69 | + private_class_method :build_client |
| 70 | + end |
| 71 | +end |
0 commit comments