nanosandbox 0.2.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9566f6f478609c1c1111f52691c0c76b36b55e3d647084c0e9523d00f363b837
4
+ data.tar.gz: 2a82de2386b4ea23810ee4cba9398020a96823c24c7363499b74f0b33bdd12e1
5
+ SHA512:
6
+ metadata.gz: 27d7e7bc5c9a63d88eff327050574e0e7bc62e864323c17bf8e4e1e4cf10559814add5f02bd6a2abe8b3591bfda734b7c4d3693e79099a059d6c682dfc0c320e
7
+ data.tar.gz: c909ae377d502955999875da57ce4c5ca840c87f374e8388fb9325ccb3d54e039e4ca1b1a3f03f4fd8a26a7f4765faffb546560b6801a6b7ec6b94a702c63b85
data/README.md ADDED
@@ -0,0 +1,116 @@
1
+ # nanosandbox — Ruby SDK
2
+
3
+ A **stdlib-only** Ruby protocol client for the nanosandbox helper
4
+ (`nanosb-protocol` v1.0.0). It speaks NDJSON over a Unix stream socket using
5
+ only the standard library (`socket`, `json`, `base64`).
6
+
7
+ The client surface mirrors the Python SDK (`sdk/python/nanosandbox/client.py`)
8
+ and the driver contract in `sdk/conformance/SPEC.md`.
9
+
10
+ ## Requirements
11
+
12
+ - Ruby 2.6+ (uses stdlib-only code; tested on the system Ruby 2.6.10).
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ gem install nanosandbox
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ```ruby
23
+ $LOAD_PATH.unshift("sdk/ruby/lib")
24
+ require "nanosandbox"
25
+ include Nanosandbox
26
+
27
+ client = SandboxClient.connect("/path/to/helper.sock")
28
+ client.supports("exec") # => true / false
29
+
30
+ spec = SandboxBuilder.new("alpine:latest")
31
+ .with_name("demo")
32
+ .with_resources(2, 512)
33
+ .publish_tcp(8080, 80)
34
+ .build
35
+ box = client.create(spec)
36
+
37
+ box.start
38
+ box.state # => "running"
39
+
40
+ res = box.exec("echo", ["hi"])
41
+ res["exit_code"] # => 0
42
+
43
+ code = box.exec_stream({ "command" => "echo", "args" => ["hi"] }) do |ev|
44
+ $stdout.write(ev["data"]) if ev["event"] == "stdout"
45
+ end
46
+
47
+ box.fs_write("/tmp/x", "hello")
48
+ box.fs_read("/tmp/x") # => "hello"
49
+ box.logs_with(10, 0, "stdout")
50
+ box.metrics
51
+ box.volume_create("data", "/host/volumes/data")
52
+ box.secret_set("API_KEY", "s3cr3t")
53
+
54
+ begin
55
+ client.get("missing")
56
+ rescue NanosbError => e
57
+ e.code # => "not_found"
58
+ end
59
+ ```
60
+
61
+ Every call dials a fresh connection and re-negotiates the `hello` handshake
62
+ (stateless). Streaming verbs (`exec_stream`, `attach`, `logs` with `follow`,
63
+ `metrics_stream`, `fs_write_stream`) hold one connection for the stream: an
64
+ opening `ok` ack, then frames until the terminal frame (`guest exit/error` or
65
+ `event done`).
66
+
67
+ ## Managing a real sandbox (`ManagedRuntime`)
68
+
69
+ `Nanosandbox::ManagedRuntime` locates and starts the real `nanosb-runtime` helper
70
+ so you can boot and manage microVMs without launching it yourself:
71
+
72
+ ```ruby
73
+ require "nanosandbox/runtime"
74
+
75
+ Nanosandbox::ManagedRuntime.open do |rt|
76
+ client = Nanosandbox::SandboxClient.connect(rt.socket)
77
+ box = client.create("image" => "library/alpine:latest", "name" => "demo")
78
+ puts box.exec("echo", ["hello from a microVM"])["stdout"]
79
+ end
80
+ ```
81
+
82
+ The helper is found via `NANOSB_RUNTIME_BIN` → `$NANOSB_HOME/bin/nanosb-runtime`
83
+ → `PATH` → the repo `target/debug/nanosb-runtime`.
84
+
85
+ ## Testing
86
+
87
+ Unit tests (minitest, in-process fake helper):
88
+
89
+ ```bash
90
+ ruby -I sdk/ruby/lib sdk/ruby/test/test_client.rb
91
+ ```
92
+
93
+ Conformance driver — runs all 35 scenarios in `sdk/conformance/scenarios/`:
94
+
95
+ ```bash
96
+ ruby -I sdk/ruby/lib sdk/ruby/conformance/run.rb
97
+ # NANOSB_CONFORMANCE_BIN=/path/to/nanosb-conformance ruby -I sdk/ruby/lib sdk/ruby/conformance/run.rb
98
+ ```
99
+
100
+ Expected output: `35 passed, 0 failed`, exit code 0.
101
+
102
+ Live microVM E2E (opt-in; needs the helper + libkrun/gvproxy + a cached image):
103
+
104
+ ```bash
105
+ NANOSB_E2E=1 ruby -I sdk/ruby/lib sdk/ruby/test/test_e2e.rb
106
+ ```
107
+
108
+ ## Layout
109
+
110
+ ```
111
+ sdk/ruby/
112
+ ├── lib/nanosandbox.rb # Conn, NanosbError, builders, Sandbox, SandboxClient
113
+ ├── test/test_client.rb # minitest + fake NDJSON helper
114
+ ├── conformance/run.rb # conformance driver
115
+ └── README.md
116
+ ```
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Managed nanosandbox runtime: locate the helper, spawn it, and connect.
4
+ #
5
+ # Lets a Ruby SDK user manage real sandboxes without starting the helper by
6
+ # hand. The helper (`nanosb-runtime serve`) owns the microVM lifecycle; SDK
7
+ # calls are protocol messages over its Unix socket.
8
+ #
9
+ # Nanosandbox::ManagedRuntime.open do |rt|
10
+ # client = Nanosandbox::SandboxClient.connect(rt.socket)
11
+ # box = client.create("image" => "library/alpine:latest", "name" => "demo")
12
+ # puts box.exec("echo", ["hi"])["stdout"]
13
+ # end
14
+
15
+ require "tmpdir"
16
+ require "fileutils"
17
+
18
+ module Nanosandbox
19
+ # Locate the nanosb-runtime helper, in order of preference.
20
+ def self.find_runtime_bin
21
+ env = ENV["NANOSB_RUNTIME_BIN"]
22
+ return env if env && File.exist?(env)
23
+
24
+ home = ENV["NANOSB_HOME"] || File.join(Dir.home, ".nanosandbox")
25
+ candidate = File.join(home, "bin", "nanosb-runtime")
26
+ return candidate if File.exist?(candidate)
27
+
28
+ which = `which nanosb-runtime 2>/dev/null`.strip
29
+ return which unless which.empty?
30
+
31
+ repo = File.expand_path("../../../..", __dir__) # lib/nanosandbox/runtime.rb -> repo root
32
+ dev = File.join(repo, "target", "debug", "nanosb-runtime")
33
+ return dev if File.exist?(dev)
34
+
35
+ nil
36
+ end
37
+
38
+ # A running nanosb-runtime helper on a private socket.
39
+ class ManagedRuntime
40
+ attr_reader :dir, :socket, :pid
41
+
42
+ def initialize(binary: nil, wait_secs: 15)
43
+ @binary = binary || Nanosandbox.find_runtime_bin
44
+ raise "nanosb-runtime not found; set NANOSB_RUNTIME_BIN or build it" unless @binary
45
+
46
+ @dir = Dir.mktmpdir("nanosb-e2e-")
47
+ @socket = File.join(@dir, "helper.sock")
48
+ @pid = spawn(@binary, "serve", "--socket", @socket, out: File::NULL, err: File::NULL)
49
+ deadline = Time.now + wait_secs
50
+ until File.exist?(@socket)
51
+ raise "timed out waiting for the helper socket" if Time.now > deadline
52
+ raise "nanosb-runtime exited before opening its socket" unless alive?
53
+
54
+ sleep 0.05
55
+ end
56
+ end
57
+
58
+ def alive?
59
+ Process.kill(0, @pid)
60
+ true
61
+ rescue Errno::ESRCH, Errno::EPERM
62
+ false
63
+ end
64
+
65
+ def close
66
+ begin
67
+ Process.kill("TERM", @pid)
68
+ Process.wait(@pid)
69
+ rescue StandardError
70
+ begin
71
+ Process.kill("KILL", @pid)
72
+ rescue StandardError
73
+ nil
74
+ end
75
+ end
76
+ FileUtils.remove_entry(@dir) if @dir && File.directory?(@dir)
77
+ end
78
+
79
+ def self.open(**kwargs)
80
+ rt = new(**kwargs)
81
+ return rt unless block_given?
82
+
83
+ begin
84
+ yield rt
85
+ ensure
86
+ rt.close
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,764 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Protocol client for the nanosandbox helper (nanosb-protocol v1.0.0).
4
+ #
5
+ # Mirrors sdk/python/nanosandbox/client.py. Each call dials a fresh connection
6
+ # and re-negotiates the hello handshake (stateless).
7
+
8
+ require "socket"
9
+ require "json"
10
+ require "base64"
11
+
12
+ module Nanosandbox
13
+ PROTOCOL_VERSION = "1.0.0"
14
+ CLIENT_NAME = "nanosandbox-ruby"
15
+
16
+ class NanosbError < StandardError
17
+ attr_reader :code, :message
18
+
19
+ def initialize(code, message)
20
+ @code = code
21
+ @message = message
22
+ super("#{code}: #{message}")
23
+ end
24
+
25
+ def is_not_found?
26
+ @code == "not_found"
27
+ end
28
+ end
29
+
30
+ def self.b64(data)
31
+ Base64.strict_encode64(data)
32
+ end
33
+
34
+ def self.unb64(text)
35
+ Base64.decode64(text)
36
+ end
37
+
38
+ # One negotiated connection (dial -> hello -> request -> response).
39
+ class Conn
40
+ attr_reader :hello, :sock
41
+
42
+ def initialize(path, client_name = CLIENT_NAME)
43
+ @sock = Socket.new(Socket::AF_UNIX, Socket::SOCK_STREAM, 0)
44
+ @sock.connect(Socket.pack_sockaddr_un(path))
45
+ @hello = handshake(client_name)
46
+ end
47
+
48
+ def handshake(client_name)
49
+ send_msg(
50
+ "type" => "hello",
51
+ "client" => client_name,
52
+ "sdk_version" => PROTOCOL_VERSION,
53
+ "protocol_min" => PROTOCOL_VERSION,
54
+ "protocol_max" => PROTOCOL_VERSION
55
+ )
56
+ resp = recv
57
+ unless resp["type"] == "hello_ok"
58
+ raise NanosbError.new(resp["code"] || "internal", resp["message"] || "bad handshake")
59
+ end
60
+ unless resp["protocol"] == PROTOCOL_VERSION
61
+ raise NanosbError.new("incompatible_version",
62
+ "helper speaks #{resp['protocol']}, client needs #{PROTOCOL_VERSION}")
63
+ end
64
+ resp
65
+ end
66
+
67
+ def send_msg(message)
68
+ @sock.write(JSON.generate(message) + "\n")
69
+ end
70
+
71
+ def recv
72
+ line = @sock.gets
73
+ raise NanosbError.new("transport", "connection closed") if line.nil?
74
+
75
+ JSON.parse(line)
76
+ end
77
+
78
+ def call(message)
79
+ send_msg(message)
80
+ resp = recv
81
+ if resp["type"] == "error"
82
+ raise NanosbError.new(resp["code"] || "internal", resp["message"] || "")
83
+ end
84
+ resp
85
+ end
86
+
87
+ def close
88
+ @sock.close unless @sock.closed?
89
+ end
90
+ end
91
+
92
+ # Fluent builder for a sandbox creation spec.
93
+ class SandboxBuilder
94
+ def initialize(image)
95
+ @image = image
96
+ @name = nil
97
+ @cpus = nil
98
+ @memory_mb = nil
99
+ @env = {}
100
+ @mounts = []
101
+ @network = {}
102
+ @workdir = nil
103
+ @timeout_secs = nil
104
+ @user = nil
105
+ @home = nil
106
+ @command = nil
107
+ @command_args = []
108
+ @labels = {}
109
+ @ephemeral = false
110
+ @replace = false
111
+ @detached = true
112
+ @hostname = nil
113
+ @secret_env = {}
114
+ end
115
+
116
+ def with_name(name)
117
+ @name = name
118
+ self
119
+ end
120
+
121
+ def with_resources(cpus, memory_mb)
122
+ @cpus = cpus
123
+ @memory_mb = memory_mb
124
+ self
125
+ end
126
+
127
+ def with_env(key, value)
128
+ @env[key] = value
129
+ self
130
+ end
131
+
132
+ def with_label(key, value)
133
+ @labels[key] = value
134
+ self
135
+ end
136
+
137
+ def mount(host_path, guest_path, readonly = false)
138
+ @mounts << {
139
+ "host_path" => host_path,
140
+ "guest_path" => guest_path,
141
+ "readonly" => readonly,
142
+ "mount_type" => "virtiofs"
143
+ }
144
+ self
145
+ end
146
+
147
+ def publish_tcp(host_port, guest_port)
148
+ @network["enabled"] = true
149
+ (@network["publish"] ||= []) << {
150
+ "host_port" => host_port, "container_port" => guest_port, "protocol" => "tcp"
151
+ }
152
+ self
153
+ end
154
+
155
+ def publish_udp(host_port, guest_port)
156
+ @network["enabled"] = true
157
+ (@network["publish"] ||= []) << {
158
+ "host_port" => host_port, "container_port" => guest_port, "protocol" => "udp"
159
+ }
160
+ self
161
+ end
162
+
163
+ def detached(detached)
164
+ @detached = detached
165
+ self
166
+ end
167
+
168
+ def hostname(hostname)
169
+ @hostname = hostname
170
+ self
171
+ end
172
+
173
+ def mount_file(host_path, guest_path)
174
+ @mounts << {
175
+ "host_path" => host_path, "guest_path" => guest_path, "readonly" => false,
176
+ "mount_type" => "virtiofs", "file" => true
177
+ }
178
+ self
179
+ end
180
+
181
+ def mount_tmpfs(guest_path)
182
+ @mounts << {
183
+ "host_path" => "", "guest_path" => guest_path, "readonly" => false,
184
+ "mount_type" => "tmpfs", "tmpfs" => true
185
+ }
186
+ self
187
+ end
188
+
189
+ def mount_options(options)
190
+ @mounts.last["options"] = options.dup unless @mounts.empty?
191
+ self
192
+ end
193
+
194
+ def mount_owner(uid, gid)
195
+ unless @mounts.empty?
196
+ @mounts.last["uid"] = uid
197
+ @mounts.last["gid"] = gid
198
+ end
199
+ self
200
+ end
201
+
202
+ def secret_env(key, secret_key)
203
+ @secret_env[key] = secret_key
204
+ self
205
+ end
206
+
207
+ def build
208
+ spec = { "image" => @image, "detached" => @detached }
209
+ {
210
+ "name" => @name, "cpus" => @cpus, "memory_mb" => @memory_mb,
211
+ "workdir" => @workdir, "timeout_secs" => @timeout_secs,
212
+ "user" => @user, "home" => @home, "command" => @command
213
+ }.each do |k, v|
214
+ spec[k] = v unless v.nil?
215
+ end
216
+ spec["hostname"] = @hostname unless @hostname.nil?
217
+ spec["env"] = @env unless @env.empty?
218
+ spec["mounts"] = @mounts unless @mounts.empty?
219
+ spec["network"] = @network unless @network.empty?
220
+ spec["command_args"] = @command_args unless @command_args.empty?
221
+ spec["labels"] = @labels unless @labels.empty?
222
+ spec["ephemeral"] = true if @ephemeral
223
+ spec["replace"] = true if @replace
224
+ spec["secret_env"] = @secret_env unless @secret_env.empty?
225
+ spec
226
+ end
227
+ end
228
+
229
+ # Fluent builder for a volume creation spec.
230
+ class VolumeBuilder
231
+ def initialize(name)
232
+ @name = name
233
+ @dir = nil
234
+ @disk_image = nil
235
+ @fstype = nil
236
+ @quota_bytes = nil
237
+ end
238
+
239
+ def with_dir(dir)
240
+ @dir = dir
241
+ self
242
+ end
243
+
244
+ def disk_image(image)
245
+ @disk_image = image
246
+ self
247
+ end
248
+
249
+ def fstype(fstype)
250
+ @fstype = fstype
251
+ self
252
+ end
253
+
254
+ def volume_quota(bytes)
255
+ @quota_bytes = bytes
256
+ self
257
+ end
258
+
259
+ def build
260
+ spec = { "name" => @name }
261
+ { "dir" => @dir, "disk_image" => @disk_image,
262
+ "fstype" => @fstype, "quota_bytes" => @quota_bytes }.each do |k, v|
263
+ spec[k] = v unless v.nil?
264
+ end
265
+ spec
266
+ end
267
+ end
268
+
269
+ # A live attach session: drive input/resize and read events on one connection.
270
+ class AttachSession
271
+ def initialize(conn)
272
+ @conn = conn
273
+ end
274
+
275
+ def send_input(data)
276
+ text = data.dup.force_encoding("UTF-8")
277
+ @conn.call("type" => "attach_input", "data" => text)
278
+ end
279
+
280
+ def resize(cols, rows)
281
+ @conn.call("type" => "attach_resize", "cols" => cols, "rows" => rows)
282
+ end
283
+
284
+ # Returns the next guest event hash, or nil once the stream ends.
285
+ def read_events
286
+ loop do
287
+ resp = @conn.recv
288
+ next unless resp["type"] == "guest"
289
+
290
+ return nil if %w[exit error].include?(resp["event"])
291
+
292
+ return resp
293
+ end
294
+ end
295
+
296
+ def close
297
+ @conn.close
298
+ end
299
+ end
300
+
301
+ # A handle bound to one sandbox.
302
+ class Sandbox
303
+ attr_reader :name
304
+
305
+ def initialize(client, name)
306
+ @client = client
307
+ @name = name
308
+ end
309
+
310
+ def state
311
+ @client.call_raw("type" => "status", "name" => @name)["state"]
312
+ end
313
+
314
+ def info
315
+ @client.get(@name)
316
+ end
317
+
318
+ def start
319
+ @client.call_raw("type" => "start", "name" => @name)
320
+ end
321
+
322
+ def stop(force = false)
323
+ @client.call_raw("type" => "stop", "name" => @name, "force" => force)
324
+ end
325
+
326
+ def kill
327
+ @client.call_raw("type" => "kill", "name" => @name)
328
+ end
329
+
330
+ def remove(force = false)
331
+ @client.call_raw("type" => "remove", "name" => @name, "force" => force)
332
+ end
333
+
334
+ def pause
335
+ @client.call_raw("type" => "pause", "name" => @name)
336
+ end
337
+
338
+ def resume
339
+ @client.call_raw("type" => "resume", "name" => @name)
340
+ end
341
+
342
+ def touch
343
+ @client.call_raw("type" => "touch", "name" => @name)
344
+ end
345
+
346
+ def drain
347
+ @client.call_raw("type" => "drain", "name" => @name)
348
+ end
349
+
350
+ def modify(spec)
351
+ @client.call_raw("type" => "modify", "name" => @name, "spec" => spec)
352
+ end
353
+
354
+ def wait_until_stopped(timeout_secs = 30.0)
355
+ deadline = Time.now + timeout_secs
356
+ loop do
357
+ st = state
358
+ return st if st == "stopped"
359
+ raise NanosbError.new("internal", "sandbox entered error state") if st == "error"
360
+
361
+ if Time.now >= deadline
362
+ raise NanosbError.new("timeout", "sandbox '#{@name}' did not stop within #{timeout_secs}s")
363
+ end
364
+ sleep 0.1
365
+ end
366
+ end
367
+
368
+ def exec(command, args = nil)
369
+ exec_with("command" => command, "args" => args || [])
370
+ end
371
+
372
+ def exec_with(request)
373
+ req = request.dup
374
+ req["type"] = "exec"
375
+ req["name"] = @name
376
+ req["args"] ||= []
377
+ @client.call_raw(req)
378
+ end
379
+
380
+ def shell(script)
381
+ @client.call_raw("type" => "shell", "name" => @name, "script" => script)
382
+ end
383
+
384
+ def exec_stream(request, &on_event)
385
+ req = request.dup
386
+ req["type"] = "exec_stream"
387
+ req["name"] = @name
388
+ req["args"] ||= []
389
+ code = -1
390
+ conn = Conn.new(@client.socket)
391
+ begin
392
+ conn.send_msg(req)
393
+ ack = conn.recv
394
+ raise NanosbError.new(ack["code"] || "internal", ack["message"] || "") if ack["type"] == "error"
395
+
396
+ loop do
397
+ resp = conn.recv
398
+ next unless resp["type"] == "guest"
399
+
400
+ event = resp["event"]
401
+ if event == "exit"
402
+ code = resp["code"] || -1
403
+ on_event.call(resp) if on_event
404
+ break
405
+ end
406
+ if event == "error"
407
+ on_event.call(resp) if on_event
408
+ raise NanosbError.new("internal", resp["message"] || "")
409
+ end
410
+ on_event.call(resp) if on_event
411
+ end
412
+ ensure
413
+ conn.close
414
+ end
415
+ code
416
+ end
417
+
418
+ def shell_stream(script, &on_event)
419
+ exec_stream({ "command" => script, "shell" => true }, &on_event)
420
+ end
421
+
422
+ def attach(&on_event)
423
+ conn = Conn.new(@client.socket)
424
+ begin
425
+ conn.send_msg("type" => "attach", "name" => @name)
426
+ ack = conn.recv
427
+ raise NanosbError.new(ack["code"] || "internal", ack["message"] || "") if ack["type"] == "error"
428
+
429
+ loop do
430
+ resp = conn.recv
431
+ next unless resp["type"] == "guest"
432
+
433
+ on_event.call(resp) if on_event
434
+ break if %w[exit error].include?(resp["event"])
435
+ end
436
+ ensure
437
+ conn.close
438
+ end
439
+ end
440
+
441
+ def attach_session
442
+ conn = Conn.new(@client.socket)
443
+ conn.send_msg("type" => "attach", "name" => @name)
444
+ ack = conn.recv
445
+ if ack["type"] == "error"
446
+ conn.close
447
+ raise NanosbError.new(ack["code"] || "internal", ack["message"] || "")
448
+ end
449
+ AttachSession.new(conn)
450
+ end
451
+
452
+ def metrics
453
+ @client.call_raw("type" => "metrics", "name" => @name)
454
+ end
455
+
456
+ def metrics_stream(interval_ms, &on_event)
457
+ req = { "type" => "metrics_stream", "name" => @name }
458
+ req["interval_ms"] = interval_ms unless interval_ms.nil?
459
+ conn = Conn.new(@client.socket)
460
+ begin
461
+ conn.send_msg(req)
462
+ ack = conn.recv
463
+ raise NanosbError.new(ack["code"] || "internal", ack["message"] || "") if ack["type"] == "error"
464
+
465
+ loop do
466
+ resp = conn.recv
467
+ next unless resp["type"] == "event"
468
+
469
+ break if resp["event"] == "done"
470
+
471
+ on_event.call(resp) if on_event && resp["event"] == "metrics"
472
+ end
473
+ ensure
474
+ conn.close
475
+ end
476
+ end
477
+
478
+ def logs(tail = nil)
479
+ req = { "type" => "logs", "name" => @name, "follow" => false }
480
+ req["tail"] = tail unless tail.nil?
481
+ @client.call_raw(req)["lines"]
482
+ end
483
+
484
+ def logs_with(tail = nil, cursor = nil, source = nil)
485
+ req = { "type" => "logs", "name" => @name, "follow" => false }
486
+ req["tail"] = tail unless tail.nil?
487
+ req["cursor"] = cursor unless cursor.nil?
488
+ req["source"] = source unless source.nil?
489
+ @client.call_raw(req)["lines"]
490
+ end
491
+
492
+ def logs_follow(tail = nil, &on_line)
493
+ logs_follow_with(tail, nil, nil, &on_line)
494
+ end
495
+
496
+ def logs_follow_with(tail = nil, cursor = nil, source = nil, &on_line)
497
+ req = { "type" => "logs", "name" => @name, "follow" => true }
498
+ req["tail"] = tail unless tail.nil?
499
+ req["cursor"] = cursor unless cursor.nil?
500
+ req["source"] = source unless source.nil?
501
+ conn = Conn.new(@client.socket)
502
+ begin
503
+ conn.send_msg(req)
504
+ ack = conn.recv
505
+ raise NanosbError.new(ack["code"] || "internal", ack["message"] || "") if ack["type"] == "error"
506
+
507
+ loop do
508
+ resp = conn.recv
509
+ next unless resp["type"] == "event"
510
+
511
+ break if resp["event"] == "done"
512
+
513
+ on_line.call(resp) if on_line && resp["event"] == "log"
514
+ end
515
+ ensure
516
+ conn.close
517
+ end
518
+ end
519
+
520
+ def fs_read(path, offset = nil, length = nil)
521
+ req = { "type" => "fs_read", "name" => @name, "path" => path }
522
+ req["offset"] = offset unless offset.nil?
523
+ req["length"] = length unless length.nil?
524
+ Nanosandbox.unb64(@client.call_raw(req)["data_base64"])
525
+ end
526
+
527
+ def fs_read_range(path, offset, length)
528
+ Nanosandbox.unb64(
529
+ @client.call_raw(
530
+ "type" => "fs_read", "name" => @name, "path" => path, "offset" => offset, "length" => length
531
+ )["data_base64"]
532
+ )
533
+ end
534
+
535
+ def fs_read_stream(path, chunk_size, &on_chunk)
536
+ chunk_size = 1 if chunk_size < 1
537
+ offset = 0
538
+ loop do
539
+ chunk = fs_read_range(path, offset, chunk_size)
540
+ break if chunk.empty?
541
+
542
+ on_chunk.call(chunk) if on_chunk
543
+ break if chunk.bytesize < chunk_size
544
+
545
+ offset += chunk.bytesize
546
+ end
547
+ end
548
+
549
+ def fs_write_stream(path, data, chunk_size)
550
+ conn = Conn.new(@client.socket)
551
+ begin
552
+ conn.send_msg("type" => "fs_write_stream", "name" => @name, "path" => path)
553
+ ack = conn.recv
554
+ raise NanosbError.new(ack["code"] || "internal", ack["message"] || "") if ack["type"] == "error"
555
+
556
+ chunk_size = 1 if chunk_size < 1
557
+ chunks = []
558
+ i = 0
559
+ while i < data.bytesize
560
+ chunks << data.byteslice(i, chunk_size)
561
+ i += chunk_size
562
+ end
563
+ chunks = [""] if chunks.empty?
564
+ chunks.each_with_index do |chunk, idx|
565
+ conn.call("type" => "fs_data", "data_base64" => Nanosandbox.b64(chunk),
566
+ "eof" => idx == chunks.length - 1)
567
+ end
568
+ ensure
569
+ conn.close
570
+ end
571
+ end
572
+
573
+ def fs_read_to_string(path)
574
+ @client.call_raw("type" => "fs_read_to_string", "name" => @name, "path" => path)["content"]
575
+ end
576
+
577
+ def fs_write(path, data, append = false)
578
+ @client.call_raw("type" => "fs_write", "name" => @name, "path" => path,
579
+ "data_base64" => Nanosandbox.b64(data), "append" => append)
580
+ end
581
+
582
+ def fs_list(path)
583
+ @client.call_raw("type" => "fs_list", "name" => @name, "path" => path)["entries"]
584
+ end
585
+
586
+ def fs_stat(path)
587
+ @client.call_raw("type" => "fs_stat", "name" => @name, "path" => path)
588
+ end
589
+
590
+ def fs_exists(path)
591
+ @client.call_raw("type" => "fs_exists", "name" => @name, "path" => path)["exists"]
592
+ end
593
+
594
+ def fs_mkdir(path, recursive = false)
595
+ @client.call_raw("type" => "fs_mkdir", "name" => @name, "path" => path, "recursive" => recursive)
596
+ end
597
+
598
+ def fs_remove(path)
599
+ @client.call_raw("type" => "fs_remove", "name" => @name, "path" => path)
600
+ end
601
+
602
+ def fs_remove_dir(path, recursive = false)
603
+ @client.call_raw("type" => "fs_remove_dir", "name" => @name, "path" => path, "recursive" => recursive)
604
+ end
605
+
606
+ def fs_copy(src, dst)
607
+ @client.call_raw("type" => "fs_copy", "name" => @name, "from" => src, "to" => dst)
608
+ end
609
+
610
+ def fs_rename(src, dst)
611
+ @client.call_raw("type" => "fs_rename", "name" => @name, "from" => src, "to" => dst)
612
+ end
613
+
614
+ def fs_copy_from_host(host_path, guest_path)
615
+ @client.call_raw("type" => "fs_copy_from_host", "name" => @name,
616
+ "host_path" => host_path, "guest_path" => guest_path)
617
+ end
618
+
619
+ def fs_copy_to_host(guest_path, host_path)
620
+ @client.call_raw("type" => "fs_copy_to_host", "name" => @name,
621
+ "host_path" => host_path, "guest_path" => guest_path)
622
+ end
623
+
624
+ def volume_create(name, dir = nil)
625
+ @client.call_raw("type" => "volume_create", "name" => @name,
626
+ "volume" => { "name" => name, "dir" => dir })
627
+ end
628
+
629
+ def volume_list
630
+ @client.call_raw("type" => "volume_list", "name" => @name)["volumes"]
631
+ end
632
+
633
+ def volume_get(volume)
634
+ @client.call_raw("type" => "volume_get", "name" => @name, "volume" => volume)
635
+ end
636
+
637
+ def volume_remove(volume)
638
+ @client.call_raw("type" => "volume_remove", "name" => @name, "volume" => volume)
639
+ end
640
+
641
+ def volume_fs(name)
642
+ info = volume_get(name)
643
+ return info["dir"] if info && info["dir"]
644
+
645
+ home = ENV["NANOSB_HOME"] || File.join(Dir.home, ".nanosandbox")
646
+ File.join(home, "volumes", name)
647
+ end
648
+
649
+ def mount_add(mount)
650
+ @client.call_raw("type" => "mount_add", "name" => @name, "mount" => mount)
651
+ end
652
+
653
+ def secret_set(key, value)
654
+ @client.call_raw("type" => "secret_set", "name" => @name, "key" => key, "value" => value)
655
+ end
656
+
657
+ def secret_list
658
+ @client.call_raw("type" => "secret_list", "name" => @name)["secrets"]
659
+ end
660
+
661
+ def secret_remove(key)
662
+ @client.call_raw("type" => "secret_remove", "name" => @name, "key" => key)
663
+ end
664
+
665
+ def snapshot_create(dest = nil)
666
+ @client.call_raw("type" => "snapshot_create", "name" => @name,
667
+ "dest" => dest, "include_memory" => false)
668
+ end
669
+
670
+ def snapshot_restore(snapshot, name)
671
+ @client.call_raw("type" => "snapshot_restore", "snapshot" => snapshot, "name" => name)
672
+ end
673
+
674
+ def snapshot_fork(snapshot, name)
675
+ @client.call_raw("type" => "snapshot_fork", "snapshot" => snapshot, "name" => name)
676
+ end
677
+
678
+ def snapshot_remove(snapshot)
679
+ @client.call_raw("type" => "snapshot_remove", "snapshot" => snapshot)
680
+ end
681
+ end
682
+
683
+ # A protocol client. Each call dials and re-negotiates (stateless).
684
+ class SandboxClient
685
+ attr_reader :socket
686
+
687
+ def initialize(socket_path)
688
+ @socket = socket_path
689
+ conn = Conn.new(socket_path)
690
+ begin
691
+ @caps = conn.hello["capabilities"] || []
692
+ ensure
693
+ conn.close
694
+ end
695
+ end
696
+
697
+ def self.connect(socket_path)
698
+ new(socket_path)
699
+ end
700
+
701
+ def capabilities
702
+ @caps.dup
703
+ end
704
+
705
+ def supports(capability)
706
+ @caps.include?(capability)
707
+ end
708
+
709
+ def call_raw(message)
710
+ conn = Conn.new(@socket)
711
+ begin
712
+ conn.call(message)
713
+ ensure
714
+ conn.close
715
+ end
716
+ end
717
+
718
+ def ping
719
+ call_raw("type" => "ping")["version"]
720
+ end
721
+
722
+ def list(all = false, label = nil)
723
+ req = { "type" => "list", "all" => all }
724
+ req["label"] = label unless label.nil?
725
+ call_raw(req)["sandboxes"]
726
+ end
727
+
728
+ def list_with_label(label, all = false)
729
+ call_raw("type" => "list", "all" => all, "label" => label)["sandboxes"]
730
+ end
731
+
732
+ def list_page(limit = nil, cursor = nil, label = nil)
733
+ req = { "type" => "list", "all" => true }
734
+ req["limit"] = limit unless limit.nil?
735
+ req["cursor"] = cursor unless cursor.nil?
736
+ req["label"] = label unless label.nil?
737
+ call_raw(req)
738
+ end
739
+
740
+ def snapshots
741
+ call_raw("type" => "snapshot_list")["snapshots"]
742
+ end
743
+
744
+ def get(name)
745
+ call_raw("type" => "get", "name" => name)
746
+ end
747
+
748
+ def create(spec)
749
+ call_raw("type" => "create", "spec" => spec)
750
+ Sandbox.new(self, spec["name"])
751
+ end
752
+
753
+ def create_with(builder)
754
+ spec = builder.build
755
+ raise ArgumentError, "spec.name is required to create" unless spec.key?("name")
756
+
757
+ create(spec)
758
+ end
759
+
760
+ def sandbox(name)
761
+ Sandbox.new(self, name)
762
+ end
763
+ end
764
+ end
metadata ADDED
@@ -0,0 +1,49 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nanosandbox
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - DevDone Labs
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-16 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Stdlib-only Ruby protocol client for the nanosandbox helper (nanosb-protocol
14
+ v1.0.0).
15
+ email:
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - README.md
21
+ - lib/nanosandbox.rb
22
+ - lib/nanosandbox/runtime.rb
23
+ homepage: https://github.com/nanosandboxai/nanosandbox
24
+ licenses:
25
+ - Apache-2.0
26
+ metadata:
27
+ homepage_uri: https://github.com/nanosandboxai/nanosandbox
28
+ source_code_uri: https://github.com/nanosandboxai/nanosandbox/tree/main/sdk/ruby
29
+ github_repo: https://github.com/nanosandboxai/nanosandbox
30
+ post_install_message:
31
+ rdoc_options: []
32
+ require_paths:
33
+ - lib
34
+ required_ruby_version: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - ">="
37
+ - !ruby/object:Gem::Version
38
+ version: '2.6'
39
+ required_rubygems_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: '0'
44
+ requirements: []
45
+ rubygems_version: 3.5.22
46
+ signing_key:
47
+ specification_version: 4
48
+ summary: Ruby SDK for the nanosandbox protocol helper
49
+ test_files: []