ruby-ship 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,288 @@
1
+ require "yaml"
2
+ require "etc"
3
+
4
+ module Ship
5
+ class Compose
6
+ ENV_VAR = /(?<!\$)\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?[-+?])([^}]*))?\}|(?<!\$)\$([A-Za-z_][A-Za-z0-9_]*)/
7
+ DEFAULT_HTTP = { "mailpit" => [8025], "rabbitmq" => [15672], "selenium" => [4444],
8
+ "meilisearch" => [7700], "centrifugo" => [8000], "mercure" => [80], "anycable" => [8080],
9
+ "silo" => [9001], "node" => [5173] }.freeze
10
+ PORT_DEFAULTS = {
11
+ "anycable" => ["ANYCABLE_PORT", 8080], "centrifugo" => ["CENTRIFUGO_PORT", 8001],
12
+ "mercure" => ["MERCURE_PORT", 8002], "node" => ["VITE_PORT", 5173], "silo" => ["SILO_CONSOLE_PORT", 9001]
13
+ }.freeze
14
+ PORT_LABELS = {
15
+ ["clickhouse", 8123] => "ClickHouse HTTP", ["clickhouse", 9000] => "ClickHouse native SQL",
16
+ ["rabbitmq", 5672] => "RabbitMQ AMQP", ["rabbitmq", 15672] => "RabbitMQ management",
17
+ ["garage", 3900] => "Garage S3", ["garage", 3903] => "Garage admin",
18
+ ["seaweedfs", 8333] => "SeaweedFS S3", ["seaweedfs", 8888] => "SeaweedFS filer",
19
+ ["silo", 9001] => "Silo console", ["mailpit", 8025] => "Mailpit inbox", ["mailpit", 1025] => "Mailpit SMTP"
20
+ }.freeze
21
+ INFRASTRUCTURE_SECRETS = {
22
+ "mysql" => %w[DB_ROOT_PASSWORD], "mariadb" => %w[DB_ROOT_PASSWORD], "sqlserver" => %w[DB_ROOT_PASSWORD],
23
+ "mongodb" => %w[MONGODB_ROOT_PASSWORD MONGODB_ROOT_USER], "garage" => %w[GARAGE_RPC_SECRET GARAGE_ADMIN_TOKEN]
24
+ }.freeze
25
+ attr_reader :app, :config, :services, :http, :model, :env_file, :production, :roles
26
+
27
+ def initialize(app, services, production: false)
28
+ @app, @config, @services, @production = app, app.config, services, production
29
+ @env_file = production ? ".env.production" : ".env"
30
+ @http, @roles = [], {}
31
+ @models = services.instances.to_h { |entry| [entry, entry.model(production, config)] }
32
+ @model = build_model
33
+ end
34
+
35
+ def filename = production ? "docker-compose.production.generated.yml" : "docker-compose.generated.yml"
36
+
37
+ def settings(source = model)
38
+ result = {}
39
+ YAML.dump(source).scan(ENV_VAR) do |braced, operator, default, shorthand|
40
+ key = braced || shorthand
41
+ current = result[key]
42
+ if operator&.end_with?("?")
43
+ result[key] = { "required" => true, "value" => "" }
44
+ elsif current.nil? || (!current["required"] && current["value"].empty? && operator&.end_with?("-"))
45
+ result[key] = { "required" => false, "value" => operator&.end_with?("-") ? default : "" }
46
+ end
47
+ end
48
+ result
49
+ end
50
+
51
+ def yaml = "# Generated by Ruby Ship. Put custom changes in a Compose override.\n" + YAML.dump(model)
52
+
53
+ def available_ports
54
+ legacy = legacy_ports(model.fetch("services"))
55
+ model.fetch("services").flat_map do |name, definition|
56
+ resource = config.renames.key(name) || name
57
+ provider = services.instances.find { |instance| instance.host == name }
58
+ definition.fetch("expose", []).filter_map do |exposure|
59
+ target, protocol = exposure.to_s.split("/", 2)
60
+ next unless /\A[1-9][0-9]{0,4}\z/.match?(target) && target.to_i <= 65535
61
+
62
+ port = target.to_i
63
+ protocol ||= "tcp"
64
+ next unless %w[tcp udp sctp].include?(protocol)
65
+
66
+ id = "#{resource}:#{port}#{"/#{protocol}" unless protocol == "tcp"}"
67
+ label = if name == config.app
68
+ "App HTTP"
69
+ else
70
+ PORT_LABELS.fetch([provider&.key, port], provider&.label || name)
71
+ end
72
+ variable, fallback = host_port_setting(name, port, protocol)
73
+ [id, { label: "#{label} · #{name}:#{port}/#{protocol}", variable: variable,
74
+ target: port, protocol: protocol, fallback: fallback, legacy: legacy.include?([name, port, protocol]) }]
75
+ end
76
+ end.to_h
77
+ end
78
+
79
+ def published_endpoints
80
+ port_entries(model.fetch("services")).map do |service, port, protocol|
81
+ variable, fallback = host_port_setting(service, port, protocol)
82
+ [service, port, protocol, variable, fallback]
83
+ end
84
+ end
85
+
86
+ private
87
+
88
+ def build_model
89
+ infrastructure = @models.filter_map do |instance, data|
90
+ fragment = data["compose"]
91
+ fragment = node_service if instance.key == "node" && !production
92
+ next unless fragment
93
+
94
+ roles[instance.host] = "infrastructure"
95
+ (data["http"] || []).each do |endpoint|
96
+ http << http_endpoint(instance.host, endpoint.fetch("port"), endpoint.fetch("role"), endpoint["health"], endpoint["urlSetting"])
97
+ end
98
+ fragment["restart"] ||= "unless-stopped" if production
99
+ fragment["expose"] ||= DEFAULT_HTTP[instance.key].dup if DEFAULT_HTTP.key?(instance.key)
100
+ [instance.host, fragment]
101
+ end.to_h
102
+
103
+ main = app_service(infrastructure)
104
+ roles[config.app] = "app"
105
+ http.unshift(http_endpoint(config.app, config.port, "site", app.health_path, "APP_URL"))
106
+ processes = config.processes.to_h do |key, entry|
107
+ name = config.renames.fetch(key, key)
108
+ options = entry.is_a?(Hash) ? entry : { "command" => entry }
109
+ service = main.reject { |field| %w[build expose healthcheck networks].include?(field) }
110
+ service["command"] = Config.argv(options.fetch("command"))
111
+ service["stop_grace_period"] = "60s"
112
+ roles[name] = "process"
113
+ if (endpoint = options["http"])
114
+ http << http_endpoint(name, endpoint.fetch("port"), endpoint.fetch("role"), endpoint["health"], endpoint["urlSetting"])
115
+ service["environment"] = service.fetch("environment").merge("PORT" => endpoint.fetch("port").to_s)
116
+ service["expose"] = [endpoint.fetch("port")]
117
+ service["healthcheck"] = healthcheck(endpoint.fetch("port"), endpoint["health"])
118
+ end
119
+ if options["healthcheck"]
120
+ service["healthcheck"] = probe(["CMD-SHELL", options["healthcheck"].gsub("$", "$$")])
121
+ end
122
+ [name, service]
123
+ end
124
+ stack = { config.app => main }.merge(infrastructure, processes)
125
+ port_entries(stack).each do |service, port, protocol|
126
+ binding = { "target" => port, "protocol" => protocol }
127
+ binding["host_ip"] = "127.0.0.1" unless production
128
+ variable, fallback = host_port_setting(service, port, protocol)
129
+ stack.fetch(service)["ports"] ||= []
130
+ stack.fetch(service)["ports"] << binding.merge("published" => '$' + "{#{variable}:-#{fallback}}")
131
+ end
132
+ external = config.networks.each_with_index.to_h { |name, index| ["ship_external_#{index + 1}", { "external" => true, "name" => name }] }
133
+ http.map { |endpoint| endpoint["service"] }.uniq.each do |service|
134
+ next if external.empty?
135
+
136
+ attached = stack[service]["networks"] ||= { "default" => {} }
137
+ external.each_key { |network| attached[network] = {} }
138
+ end
139
+
140
+ volumes = stack.values.flat_map { |service| service.fetch("volumes", []) }.filter_map do |volume|
141
+ source = volume.split(":", 2).first
142
+ source if /\A[a-zA-Z0-9_-]+\z/.match?(source)
143
+ end
144
+ compose = { "name" => config.name, "services" => stack }
145
+ compose["volumes"] = volumes.uniq.sort.to_h { |name| [name, {}] } unless volumes.empty?
146
+ compose["networks"] = { "default" => {} }.merge(external) unless external.empty?
147
+ add_build_secrets(compose, main, infrastructure)
148
+ compose
149
+ end
150
+
151
+ def add_build_secrets(compose, main, infrastructure)
152
+ app_secrets = config.data.fetch("build", {}).fetch("secrets", []).dup
153
+ secrets = app_secrets.to_h { |name| [name, { "file" => "./.ship-secrets/#{name}" }] }
154
+ if config.data.dig("build", "npmrc")
155
+ if production && app.node?
156
+ secrets["ship_npmrc"] = { "file" => "./.ship-secrets/npmrc" }
157
+ app_secrets << "ship_npmrc"
158
+ elsif !production && config.services["frontend"] == "node"
159
+ secrets["ship_npmrc"] = { "file" => "./.ship-secrets/npmrc" }
160
+ node = infrastructure.fetch(config.renames.fetch("node", "node"))
161
+ node["secrets"] = ["ship_npmrc"]
162
+ node["environment"]["NPM_CONFIG_USERCONFIG"] = "/run/secrets/ship_npmrc"
163
+ end
164
+ end
165
+ compose["secrets"] = secrets unless secrets.empty?
166
+ main.fetch("build")["secrets"] = app_secrets unless app_secrets.empty?
167
+ end
168
+
169
+ def app_service(infrastructure)
170
+ environment = { app.env_name => production ? "production" : "development", "PORT" => config.port.to_s }
171
+ environment["HTTP_PORT"] = config.port.to_s if production && config.server == "thruster"
172
+ environment["TARGET_PORT"] = app.thruster_target.to_s if production && config.server == "thruster"
173
+ environment["APP_URL"] = production ? '${APP_URL:-}' : "\${APP_URL:-http://localhost:#{config.port}}"
174
+ environment["SHIP_DATABASE"] = config.services["database"] if config.services.key?("database")
175
+ @models.each_value { |data| environment.merge!(data.fetch("environment", {})) }
176
+ services.instances.each do |instance|
177
+ INFRASTRUCTURE_SECRETS.fetch(instance.key, []).each { |name| environment["#{instance.prefix}#{name}"] = "" }
178
+ end
179
+ if config.processes.key?("sidekiq")
180
+ redis = environment["SIDEKIQ_REDIS_URL"] || environment["REDIS_URL"]
181
+ environment["SIDEKIQ_REDIS_URL"] = '$' + "{SIDEKIQ_REDIS_URL:-#{redis}}" if redis
182
+ end
183
+ public_build = config.data.dig("build", "publicEnv") || {}
184
+ environment.merge!(public_build.transform_values { |value| value.gsub("$", "$$") }) unless production
185
+
186
+ if app.sqlite?
187
+ environment["SHIP_SQLITE_PATH"] = "/app/storage/#{production ? 'production' : 'development'}.sqlite3"
188
+ end
189
+ build = { "context" => ".", "dockerfile" => "docker/ship/Dockerfile", "target" => production ? "production" : "development" }
190
+ build["args"] = dev_user unless production
191
+ build["args"] = public_build.transform_values { |value| value.gsub("$", "$$") } if production && !public_build.empty?
192
+ definition = {
193
+ "image" => "#{config.name}-ruby-ship:#{production ? 'production' : 'development'}",
194
+ "build" => build, "init" => true, "command" => app.command(production), "expose" => [config.port],
195
+ "env_file" => [env_file], "environment" => environment, "healthcheck" => healthcheck(config.port, app.health_path)
196
+ }
197
+ definition["restart"] = "unless-stopped" if production
198
+ volumes = production ? [] : [".:/app"]
199
+ volumes << "ship_sqlite:/app/storage" if app.sqlite?
200
+ definition["volumes"] = volumes unless volumes.empty?
201
+ dependencies = infrastructure.reject { |_, service| service.key?("profiles") }.to_h do |name, service|
202
+ [name, { "condition" => service.key?("healthcheck") ? "service_healthy" : "service_started" }]
203
+ end
204
+ definition["depends_on"] = dependencies unless dependencies.empty?
205
+ definition["networks"] = { "default" => { "aliases" => ["ship-app.test"] } } unless production
206
+ definition
207
+ end
208
+
209
+ def dev_user
210
+ use_host = config.data.fetch("hostUser", true) && RUBY_PLATFORM.include?("linux") && Process.uid > 0
211
+ { "SHIP_UID" => (use_host ? Process.uid : 1000).to_s, "SHIP_GID" => (use_host ? Process.gid : 1000).to_s }
212
+ end
213
+
214
+ def node_service
215
+ {
216
+ "image" => "#{config.name}-ruby-ship-node:development", "init" => true,
217
+ "build" => { "context" => ".", "dockerfile" => "docker/ship/node/Dockerfile", "args" => dev_user },
218
+ "working_dir" => "/app", "volumes" => [".:/app", "node_modules:/app/node_modules"],
219
+ "command" => ["sleep", "infinity"],
220
+ "environment" => { "VITE_PORT" => "5173" }.merge((config.data.dig("build", "publicEnv") || {}).transform_values { |value| value.gsub("$", "$$") })
221
+ }
222
+ end
223
+
224
+ def host_port_setting(service, port, protocol)
225
+ return ["APP_PORT", port] if service == config.app && port == config.port && protocol == "tcp"
226
+
227
+ entry = services.instances.find { |instance| instance.host == service }
228
+ if entry && protocol == "tcp" && DEFAULT_HTTP.fetch(entry.key, []).include?(port) && PORT_DEFAULTS.key?(entry.key)
229
+ variable, fallback = PORT_DEFAULTS.fetch(entry.key)
230
+ return ["#{entry.prefix}#{variable}", entry.name ? 0 : fallback]
231
+ end
232
+
233
+ resource = entry&.resource || config.renames.key(service) || service
234
+ prefix = resource.upcase.gsub("_", "__").tr("-", "_")
235
+ ["#{prefix}_HOST_PORT_#{port}#{"_#{protocol.upcase}" unless protocol == "tcp"}", 0]
236
+ end
237
+
238
+ def port_entries(stack)
239
+ if (settings = config.data["portPublishing"])
240
+ return settings.fetch(production ? "production" : "development").map do |entry|
241
+ default, target = entry.split(":", 2)
242
+ service = config.renames.fetch(default, default)
243
+ port, protocol = target.split("/", 2)
244
+ exposed = stack.fetch(service, {}).fetch("expose", []).any? do |exposure|
245
+ number, transport = exposure.to_s.split("/", 2)
246
+ number == port && (!transport || transport == (protocol || "tcp"))
247
+ end
248
+ unless exposed
249
+ raise Error, "No #{production ? 'production' : 'development'} endpoint matches #{entry}."
250
+ end
251
+
252
+ [service, Integer(port, 10), protocol || "tcp"]
253
+ end.uniq
254
+ end
255
+
256
+ legacy_ports(stack)
257
+ end
258
+
259
+ def legacy_ports(stack)
260
+ ports = []
261
+ ports << [config.app, config.port, "tcp"] if !production || config.data["publishPorts"]
262
+ unless production
263
+ services.instances.each do |entry|
264
+ next unless stack.key?(entry.host)
265
+
266
+ DEFAULT_HTTP.fetch(entry.key, []).each { |port| ports << [entry.host, port, "tcp"] }
267
+ end
268
+ end
269
+ ports
270
+ end
271
+
272
+ def http_endpoint(service, port, role, health, url_setting)
273
+ { "service" => service, "port" => port, "role" => role, "health" => health, "urlSetting" => url_setting }
274
+ end
275
+
276
+ def healthcheck(port, path)
277
+ if path
278
+ probe(["CMD", "curl", "-fsS", "--max-time", "3", "http://127.0.0.1:#{port}#{path}"])
279
+ else
280
+ probe(["CMD", "ruby", "-rsocket", "-e", "Socket.tcp('127.0.0.1', #{port}, connect_timeout: 2, &:close)"])
281
+ end
282
+ end
283
+
284
+ def probe(command)
285
+ { "test" => command, "interval" => "5s", "timeout" => "5s", "retries" => 18, "start_period" => "15s" }
286
+ end
287
+ end
288
+ end
@@ -0,0 +1,160 @@
1
+ require "json"
2
+ require "shellwords"
3
+
4
+ module Ship
5
+ class Error < StandardError; end
6
+
7
+ class Config
8
+ ROOT = File.expand_path("../..", __dir__)
9
+ SCHEMA = "https://raw.githubusercontent.com/ship-ecosystem/spec/main/schemas/ship.schema.json"
10
+ NAME = /\A[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*\z/
11
+ INSTANCE_NAME = /\A[a-z][a-z0-9_]*\z/
12
+ NETWORK = /\A[A-Za-z0-9][A-Za-z0-9_.-]*\z/
13
+ PORT = /\A[A-Za-z0-9][A-Za-z0-9_.-]*:([1-9][0-9]{0,4})(?:\/(?:udp|sctp))?\z/
14
+ ENV_NAME = /\A[A-Za-z_][A-Za-z0-9_]*\z/
15
+ KEYS = %w[$schema name framework server port services additionalServices serviceNames
16
+ externalNetwork publishPorts portPublishing extensions siloImage hostUser deployCommands
17
+ processes mongodbMode node nodeAssets build packageManager packageManagerVersion].freeze
18
+
19
+ attr_reader :data, :root
20
+
21
+ def self.read(root, required: true)
22
+ path = File.join(root, "ship.json")
23
+ return {} if !required && !File.exist?(path)
24
+
25
+ value = JSON.parse(File.read(path))
26
+ raise Error, "ship.json must contain an object." unless value.is_a?(Hash)
27
+
28
+ value
29
+ rescue Errno::ENOENT
30
+ raise Error, "ship.json is missing. Run ship init in the application directory."
31
+ rescue JSON::ParserError
32
+ raise Error, "ship.json contains invalid JSON."
33
+ end
34
+
35
+ def self.name_for(root)
36
+ name = File.basename(root).downcase.gsub(/[^a-z0-9]+/, "-").sub(/\A[^a-z]+/, "").sub(/-\z/, "")
37
+ name.empty? ? "ruby-app" : name
38
+ end
39
+
40
+ def self.argv(command)
41
+ command.is_a?(String) ? ["sh", "-lc", command] : command
42
+ end
43
+
44
+ def initialize(root, data)
45
+ @root, @data = root, data
46
+ validate!
47
+ end
48
+
49
+ def name = data.fetch("name", self.class.name_for(root))
50
+ def app = renames.fetch("app", "app")
51
+ def renames = data.fetch("serviceNames", {})
52
+ def services = data.fetch("services", {})
53
+ def instances = data.fetch("additionalServices", [])
54
+ def networks = Array(data["externalNetwork"])
55
+ def processes = data.fetch("processes", {})
56
+ def deploy = data.fetch("deployCommands", []).map { |command| Config.argv(command) }
57
+ def port = data.fetch("port", 3000)
58
+ def framework = data["framework"]
59
+ def server = data.fetch("server", "puma")
60
+
61
+ private
62
+
63
+ def validate!
64
+ problems = []
65
+ unknown = data.keys - KEYS
66
+ problems << "Unsupported Ruby Ship settings: #{unknown.join(', ')}." unless unknown.empty?
67
+ problems << "name must be a lowercase Compose project name." unless name.is_a?(String) && NAME.match?(name)
68
+ %w[framework server].each do |key|
69
+ problems << "#{key} must be a valid key." if data.key?(key) && !(data[key].is_a?(String) && NAME.match?(data[key]))
70
+ end
71
+ problems << "port must be an integer from 1 to 65535." unless valid_port?(port)
72
+ validate_string_map("services", services, problems)
73
+ validate_string_map("serviceNames", renames, problems)
74
+ valid_instances = instances.is_a?(Array) && instances.all? do |entry|
75
+ entry.is_a?(Hash) && entry.keys.sort == %w[group name service] &&
76
+ %w[group service].all? { |key| entry[key].is_a?(String) && NAME.match?(entry[key]) } &&
77
+ entry["name"].is_a?(String) && INSTANCE_NAME.match?(entry["name"])
78
+ end
79
+ problems << "additionalServices must contain valid group, service and name entries." unless valid_instances
80
+ if data.key?("externalNetwork") && (!networks.any? || networks.uniq != networks ||
81
+ !networks.all? { |value| value.is_a?(String) && NETWORK.match?(value) })
82
+ problems << "externalNetwork must be a network name or a nonempty list of unique network names."
83
+ end
84
+ %w[hostUser nodeAssets publishPorts].each do |key|
85
+ problems << "#{key} must be a boolean." if data.key?(key) && ![true, false].include?(data[key])
86
+ end
87
+ if data.key?("portPublishing")
88
+ definition = data["portPublishing"]
89
+ valid = definition.is_a?(Hash) && definition.keys.sort == %w[development production] &&
90
+ definition.values.all? do |ports|
91
+ ports.is_a?(Array) && ports.uniq == ports && ports.all? do |value|
92
+ match = PORT.match(value) if value.is_a?(String)
93
+ match && valid_port?(match[1].to_i)
94
+ end
95
+ end
96
+ problems << "portPublishing requires both development and production lists of SERVICE:PORT mappings." unless valid
97
+ end
98
+ if !processes.is_a?(Hash) || !processes.all? { |key, value| NAME.match?(key) && valid_process?(value) }
99
+ problems << "processes must contain valid names and commands, with optional healthcheck and HTTP settings."
100
+ end
101
+ commands = data.fetch("deployCommands", [])
102
+ problems << "deployCommands must contain commands." unless commands.is_a?(Array) && commands.all? { |command| valid_command?(command) }
103
+ extensions = data.fetch("extensions", [])
104
+ problems << "extensions must list unique Ruby files." unless extensions.is_a?(Array) && extensions.uniq == extensions &&
105
+ extensions.all? { |entry| entry.is_a?(String) && entry.end_with?(".rb") && !entry.empty? }
106
+ problems << "mongodbMode must be standalone or replica-set." if data.key?("mongodbMode") && !%w[standalone replica-set].include?(data["mongodbMode"])
107
+ problems << "siloImage must be standard or distroless." if data.key?("siloImage") && !%w[standard distroless].include?(data["siloImage"])
108
+ problems << "node must be a Node.js major version." if data.key?("node") && !(data["node"].is_a?(String) && /\A[1-9][0-9]*\z/.match?(data["node"]))
109
+ if data.key?("packageManager") && !%w[npm pnpm yarn bun].include?(data["packageManager"])
110
+ problems << "packageManager must be npm, pnpm, yarn, or bun."
111
+ end
112
+ if data.key?("packageManagerVersion") && !(data["packageManagerVersion"].is_a?(String) &&
113
+ /\A(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\z/.match?(data["packageManagerVersion"]))
114
+ problems << "packageManagerVersion must be a pinned version."
115
+ end
116
+ problems << "build must contain valid publicEnv, secrets, and npmrc settings." if data.key?("build") && !valid_build?(data["build"])
117
+ problems << "$schema must be a string." if data.key?("$schema") && !data["$schema"].is_a?(String)
118
+ raise Error, problems.join("\n") unless problems.empty?
119
+ end
120
+
121
+ def validate_string_map(key, value, problems)
122
+ unless value.is_a?(Hash) && value.all? { |name, entry| NAME.match?(name) && entry.is_a?(String) && NAME.match?(entry) }
123
+ problems << "#{key} must map valid names to valid names."
124
+ end
125
+ end
126
+
127
+ def valid_port?(value) = value.is_a?(Integer) && (1..65535).cover?(value)
128
+
129
+ def valid_build?(build)
130
+ return false unless build.is_a?(Hash) && (build.keys - %w[publicEnv secrets npmrc]).empty?
131
+
132
+ public_env = build.fetch("publicEnv", {})
133
+ secrets = build.fetch("secrets", [])
134
+ public_env.is_a?(Hash) && public_env.all? { |key, value| ENV_NAME.match?(key) && value.is_a?(String) && !value.include?("\0") } &&
135
+ secrets.is_a?(Array) && secrets.uniq == secrets && secrets.all? do |key|
136
+ key.is_a?(String) && ENV_NAME.match?(key) && key != "ship_npmrc" &&
137
+ !/\A(?:VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_|PUBLIC_|GATSBY_|REACT_APP_)/.match?(key)
138
+ end && [true, false].include?(build.fetch("npmrc", false))
139
+ end
140
+
141
+ def valid_command?(command)
142
+ elements = command.is_a?(Array) ? command : [command]
143
+ elements.first.is_a?(String) && !elements.first.strip.empty? &&
144
+ elements.all? { |value| value.is_a?(String) && !value.include?("\0") }
145
+ end
146
+
147
+ def valid_process?(value)
148
+ return valid_command?(value) unless value.is_a?(Hash)
149
+ return false unless (value.keys - %w[command healthcheck http]).empty? && valid_command?(value["command"])
150
+ return false if value.key?("healthcheck") && !(value["healthcheck"].is_a?(String) && valid_command?(value["healthcheck"]))
151
+ return true unless value.key?("http")
152
+
153
+ http = value["http"]
154
+ http.is_a?(Hash) && (http.keys - %w[port role health urlSetting]).empty? && valid_port?(http["port"]) &&
155
+ http["role"].is_a?(String) && !http["role"].empty? &&
156
+ (http["health"].nil? || (http["health"].is_a?(String) && http["health"].start_with?("/"))) &&
157
+ (http["urlSetting"].nil? || (http["urlSetting"].is_a?(String) && ENV_NAME.match?(http["urlSetting"])))
158
+ end
159
+ end
160
+ end
@@ -0,0 +1,123 @@
1
+ require "json"
2
+ require "open3"
3
+ require "tempfile"
4
+
5
+ module Ship
6
+ class Docker
7
+ attr_reader :project, :production
8
+
9
+ def initialize(project, production: false, files: nil, env_file: nil)
10
+ @project, @production = project, production
11
+ @files, @env_file = files, env_file
12
+ end
13
+
14
+ def compose(*args)
15
+ run(*compose_command, *args)
16
+ end
17
+
18
+ def read_compose(*args)
19
+ capture(*compose_command, *args)
20
+ end
21
+
22
+ def run(*argv, **redirects)
23
+ process = Process.spawn(*argv, chdir: project.root, **redirects)
24
+ if block_given?
25
+ until (finished = Process.wait2(process, Process::WNOHANG))
26
+ yield
27
+ sleep(0.08)
28
+ end
29
+ _, status = finished
30
+ else
31
+ _, status = Process.wait2(process)
32
+ end
33
+ status.exitstatus || 128 + status.termsig
34
+ rescue Errno::ENOENT => error
35
+ raise Error, "Cannot run #{argv.first}. #{error.message}"
36
+ end
37
+
38
+ def build(*args, terminal:, message:, verbose: false)
39
+ argv = [*compose_command, "--progress", "plain", "build", *args]
40
+ if verbose
41
+ terminal.output.puts(message)
42
+ terminal.output.flush
43
+ return run(*argv, in: File::NULL)
44
+ end
45
+
46
+ Tempfile.create(["ruby-ship-build", ".log"], binmode: true) do |log|
47
+ status = terminal.build_progress(message, log) do |update|
48
+ run(*argv, in: File::NULL, out: log, err: [:child, :out], &update)
49
+ end
50
+ unless status.zero?
51
+ log.rewind
52
+ IO.copy_stream(log, terminal.error)
53
+ terminal.error.flush
54
+ end
55
+ status
56
+ end
57
+ end
58
+
59
+ def with_development_images(*targets, terminal:, verbose: false, rebuild: true)
60
+ model = development_model(targets)
61
+ services = model.fetch("services").select { |_, definition| definition["build"] }
62
+ requested = services.keys
63
+ unless rebuild
64
+ requested = services.filter_map do |name, definition|
65
+ image = definition["image"] || "#{model.fetch('name')}-#{name}"
66
+ platform = definition["platform"] || ENV["DOCKER_DEFAULT_PLATFORM"]
67
+ flags = platform.to_s.empty? ? [] : ["--platform", platform]
68
+ _, _, present = capture("docker", "image", "inspect", *flags, image)
69
+ name if !present || %w[always build].include?(definition["pull_policy"])
70
+ end
71
+ end
72
+ if requested.any?
73
+ message = targets.length == 1 ? "Building development images for #{targets.first}…" : "Building development images for #{project.config.name}…"
74
+ status = build(*requested, terminal: terminal, message: message, verbose: verbose)
75
+ return status unless status.zero?
76
+ end
77
+ return yield self if services.empty?
78
+
79
+ # Use local tags for built services while letting registry-only services be pulled.
80
+ policies = services.transform_values { { "pull_policy" => "never" } }
81
+ Tempfile.create(["ruby-ship-images", ".json"]) do |file|
82
+ file.write(JSON.generate("services" => policies))
83
+ file.flush
84
+ yield Docker.new(project, files: [*compose_files, file.path], env_file: @env_file)
85
+ end
86
+ end
87
+
88
+ def capture(*argv)
89
+ stdout, stderr, status = Open3.capture3(*argv, chdir: project.root)
90
+ [stdout, stderr, status.success?]
91
+ rescue Errno::ENOENT => error
92
+ ["", "Cannot run #{argv.first}. #{error.message}", false]
93
+ end
94
+
95
+ def checked(*argv)
96
+ output, error, ok = capture(*argv)
97
+ raise Error, error.strip.empty? ? "#{argv.first} failed." : error.strip unless ok
98
+
99
+ output
100
+ end
101
+
102
+ def checked_compose(*args) = checked(*compose_command, *args)
103
+
104
+ def compose_command
105
+ file = @env_file || (production ? project.production.env_file : project.development.env_file)
106
+ ["docker", "compose", "--project-directory", project.root, "--env-file", file,
107
+ *compose_files.flat_map { |path| ["-f", path] }]
108
+ end
109
+
110
+ private
111
+
112
+ def compose_files = @files || project.compose_files(production)
113
+
114
+ def development_model(targets)
115
+ model = JSON.parse(checked_compose("config", "--no-env-resolution", "--format", "json", *targets))
116
+ return model if model.is_a?(Hash) && model["name"].is_a?(String) && model["services"].is_a?(Hash)
117
+
118
+ raise Error, "Docker Compose did not return a valid development service model."
119
+ rescue JSON::ParserError
120
+ raise Error, "Docker Compose did not return a valid development service model."
121
+ end
122
+ end
123
+ end