@native-sdk/cli 0.4.4 → 0.5.1
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.
- package/build/app.zig +371 -5
- package/build/ts_run.mjs +102 -0
- package/build.zig +255 -1
- package/build.zig.zon +1 -0
- package/package.json +19 -10
- package/packages/core/package-lock.json +44 -0
- package/packages/core/package.json +38 -0
- package/packages/core/rt/rt.zig +1579 -0
- package/packages/core/sdk/bytes_text_methods.d.ts +88 -0
- package/packages/core/sdk/core.ts +694 -0
- package/packages/core/sdk/events.ts +137 -0
- package/packages/core/sdk/text.ts +519 -0
- package/packages/core/src/checker.ts +1869 -0
- package/packages/core/src/cli.ts +68 -0
- package/packages/core/src/devhost.ts +291 -0
- package/packages/core/src/devhost_resolver.mjs +22 -0
- package/packages/core/src/diagnostics.ts +417 -0
- package/packages/core/src/emitter.ts +8815 -0
- package/packages/core/src/infer.ts +1515 -0
- package/packages/core/src/modules.ts +173 -0
- package/packages/core/src/ownership.ts +740 -0
- package/packages/core/src/text_polyfill.ts +337 -0
- package/packages/core/src/text_tables.ts +408 -0
- package/packages/core/src/transpile.ts +146 -0
- package/packages/core/src/typed_ast.ts +546 -0
- package/packages/core/src/types.ts +815 -0
- package/skill-data/native-ui/SKILL.md +14 -0
- package/skill-data/ts-core/SKILL.md +493 -0
- package/skill-data/zig/SKILL.md +10 -0
- package/src/app_runner/root.zig +24 -0
- package/src/app_runner/ts_core_main.zig +231 -0
- package/src/platform/windows/webview2_host.cpp +24 -0
- package/src/primitives/app_manifest/comptime_scene.zig +341 -0
- package/src/primitives/app_manifest/root.zig +5 -0
- package/src/primitives/canvas/commands.zig +14 -7
- package/src/primitives/canvas/layout_audit.zig +5 -5
- package/src/primitives/canvas/lazy_tls.zig +73 -0
- package/src/primitives/canvas/render_generic_resources.zig +22 -15
- package/src/primitives/canvas/root.zig +11 -0
- package/src/primitives/canvas/tests.zig +1 -0
- package/src/primitives/canvas/text_atlas.zig +40 -32
- package/src/primitives/canvas/text_layout_cache.zig +29 -22
- package/src/primitives/canvas/text_measure_cache.zig +56 -41
- package/src/primitives/canvas/text_spans.zig +39 -26
- package/src/primitives/canvas/tokens.zig +69 -0
- package/src/primitives/canvas/ui.zig +125 -0
- package/src/primitives/canvas/ui_markup.zig +22 -3
- package/src/primitives/canvas/ui_markup_compiled.zig +97 -7
- package/src/primitives/canvas/ui_markup_compiled_tests.zig +275 -0
- package/src/primitives/canvas/ui_markup_contract.zig +68 -14
- package/src/primitives/canvas/ui_markup_contract_tests.zig +257 -2
- package/src/primitives/canvas/ui_markup_reflect.zig +214 -0
- package/src/primitives/canvas/ui_markup_view.zig +105 -1
- package/src/primitives/canvas/ui_markup_view_tests.zig +336 -0
- package/src/primitives/canvas/ui_schema.zig +8 -0
- package/src/primitives/canvas/ui_schema_tests.zig +5 -4
- package/src/primitives/canvas/widget_builtin_tests.zig +309 -5
- package/src/primitives/canvas/widget_invalidation.zig +14 -7
- package/src/primitives/canvas/widget_layout.zig +138 -2
- package/src/primitives/canvas/widget_metrics.zig +16 -8
- package/src/primitives/canvas/widget_render.zig +25 -15
- package/src/primitives/canvas/widget_render_controls.zig +15 -9
- package/src/primitives/canvas/widget_runtime_tests.zig +44 -0
- package/src/root.zig +7 -0
- package/src/runtime/canvas_frame.zig +57 -36
- package/src/runtime/canvas_images.zig +9 -3
- package/src/runtime/canvas_widget_control_tests.zig +5 -6
- package/src/runtime/canvas_widget_runtime.zig +7 -4
- package/src/runtime/core.zig +16 -0
- package/src/runtime/effects.zig +1525 -133
- package/src/runtime/effects_fetch_tests.zig +42 -0
- package/src/runtime/effects_file_tests.zig +220 -0
- package/src/runtime/effects_host_tests.zig +594 -0
- package/src/runtime/effects_tests.zig +287 -0
- package/src/runtime/root.zig +18 -0
- package/src/runtime/session_replay.zig +7 -1
- package/src/runtime/tests.zig +2 -0
- package/src/runtime/ts_core_host.zig +1505 -0
- package/src/runtime/ts_core_host_tests.zig +1408 -0
- package/src/runtime/ts_ui_app.zig +469 -0
- package/src/runtime/ui_app.zig +189 -38
- package/src/runtime/ui_app_tests.zig +221 -0
- package/src/runtime/ui_app_window_tests.zig +182 -0
- package/src/runtime/view_canvas.zig +24 -17
- package/src/runtime/view_widget_tree.zig +2 -2
- package/src/tooling/codesign.zig +212 -105
- package/src/tooling/doctor.zig +78 -0
- package/src/tooling/manifest.zig +47 -0
- package/src/tooling/package.zig +435 -20
- package/src/tooling/raw_manifest.zig +15 -0
- package/src/tooling/root.zig +1 -0
- package/src/tooling/templates.zig +777 -34
- package/src/tooling/ts_core.zig +1099 -0
- package/src/tooling/verbs.zig +105 -2
package/src/runtime/effects.zig
CHANGED
|
@@ -149,6 +149,18 @@ pub const max_effect_file_path_bytes: usize = 1024;
|
|
|
149
149
|
/// write would corrupt the file on disk, which truncation flags cannot
|
|
150
150
|
/// undo.
|
|
151
151
|
pub const max_effect_file_bytes: usize = 1024 * 1024;
|
|
152
|
+
/// How long teardown waits (total, in milliseconds) for file workers
|
|
153
|
+
/// stuck in blocking I/O before abandoning them — the default of the
|
|
154
|
+
/// channel's injectable `file_join_deadline_ms`. File I/O is the one
|
|
155
|
+
/// effect with no converging force at teardown (nothing to kill, no
|
|
156
|
+
/// flag the OS call polls): a write to a FIFO with no reader or a read
|
|
157
|
+
/// against a stalled network filesystem can block forever. Halfway
|
|
158
|
+
/// through this budget teardown cancels the blocked task (best-effort
|
|
159
|
+
/// syscall interruption); a worker still stuck when it expires is
|
|
160
|
+
/// abandoned with a bounded, loud leak (see `Effects.deinit`). Generous
|
|
161
|
+
/// on purpose — healthy local I/O finishes in milliseconds and never
|
|
162
|
+
/// meets this bound.
|
|
163
|
+
pub const default_effect_file_join_deadline_ms: u64 = 15_000;
|
|
152
164
|
|
|
153
165
|
/// Maximum clipboard-effect payload: what one `writeClipboard` writes
|
|
154
166
|
/// and the most one `readClipboard` delivers — the platform clipboard
|
|
@@ -157,6 +169,22 @@ pub const max_effect_file_bytes: usize = 1024 * 1024;
|
|
|
157
169
|
/// must never pass for the whole one).
|
|
158
170
|
pub const max_effect_clipboard_bytes: usize = platform.max_clipboard_data_bytes;
|
|
159
171
|
|
|
172
|
+
/// Maximum bytes of a host request's (or fire-and-forget host send's)
|
|
173
|
+
/// name. Mirrors the transpiled-core command wire format, whose name
|
|
174
|
+
/// field carries a one-byte length.
|
|
175
|
+
pub const max_effect_host_name_bytes: usize = 255;
|
|
176
|
+
|
|
177
|
+
/// Maximum bytes of a host request's outbound payload (mirrors
|
|
178
|
+
/// `max_effect_fetch_payload_bytes`: a command argument, not a bulk
|
|
179
|
+
/// transfer).
|
|
180
|
+
pub const max_effect_host_payload_bytes: usize = 64 * 1024;
|
|
181
|
+
|
|
182
|
+
/// Maximum bytes of a host request's result. Mirrors the fetch body
|
|
183
|
+
/// bound: the result lands in `update` as one bytes payload, sized for
|
|
184
|
+
/// API-shaped answers. An over-bound feed delivers the err route with a
|
|
185
|
+
/// teaching message, never a silent cut.
|
|
186
|
+
pub const max_effect_host_result_bytes: usize = 256 * 1024;
|
|
187
|
+
|
|
160
188
|
/// The exit `code` reported for every non-`.exited` reason.
|
|
161
189
|
pub const effect_error_exit_code: i32 = -1;
|
|
162
190
|
|
|
@@ -190,6 +218,29 @@ pub const WindowActionBinding = struct {
|
|
|
190
218
|
minimize_fn: *const fn (context: *anyopaque, window_label: []const u8) bool,
|
|
191
219
|
};
|
|
192
220
|
|
|
221
|
+
/// Type-erased handle to the embedding host's named-command services,
|
|
222
|
+
/// bound onto the effects channel (`bindHostCalls`). This is the seam
|
|
223
|
+
/// behind `hostRequest`/`hostSend` — the generic named host call a
|
|
224
|
+
/// transpiled app core's command channel (`host`/`host_bytes`/`request`
|
|
225
|
+
/// wire records) rides into the host. Both callbacks run on the loop
|
|
226
|
+
/// thread during dispatch; `name` and `payload` are valid only for the
|
|
227
|
+
/// duration of the call (copy what outlives it). A host answers a
|
|
228
|
+
/// request by calling `Effects.feedHostResult(key, ok, bytes)` on the
|
|
229
|
+
/// loop thread — synchronously from `request_fn`, or later from an
|
|
230
|
+
/// event the host marshals back.
|
|
231
|
+
pub const HostCallBinding = struct {
|
|
232
|
+
context: *anyopaque,
|
|
233
|
+
/// Fire-and-forget named host command: no key, no result, no Msg.
|
|
234
|
+
send_fn: *const fn (context: *anyopaque, name: []const u8, payload: []const u8) void,
|
|
235
|
+
/// Keyed routed host command: perform `name` and answer through
|
|
236
|
+
/// `feedHostResult` with this `key`.
|
|
237
|
+
request_fn: *const fn (context: *anyopaque, name: []const u8, key: u64, payload: []const u8) void,
|
|
238
|
+
/// Optional abort notice: the request with `key` was replaced or
|
|
239
|
+
/// cancelled — any late `feedHostResult` for it reports
|
|
240
|
+
/// `error.EffectNotFound` and delivers nothing.
|
|
241
|
+
cancel_fn: ?*const fn (context: *anyopaque, key: u64) void = null,
|
|
242
|
+
};
|
|
243
|
+
|
|
193
244
|
/// Window-action label capacity (`Effects.closeWindow`/`minimizeWindow`):
|
|
194
245
|
/// the mirror copies the last requested label so tests can pin it.
|
|
195
246
|
pub const max_window_action_label = 64;
|
|
@@ -306,8 +357,10 @@ pub const EffectFetchOutcome = enum {
|
|
|
306
357
|
/// `body` is its (possibly truncated) body.
|
|
307
358
|
ok,
|
|
308
359
|
/// The fetch never started: all slots busy, a duplicate active key,
|
|
309
|
-
/// a malformed URL or non-http(s) scheme,
|
|
310
|
-
///
|
|
360
|
+
/// a malformed URL or non-http(s) scheme, URL/headers/payload over
|
|
361
|
+
/// capacity, or the executor could not start the exchange as a
|
|
362
|
+
/// cancelable task (an uncancelable exchange would evade `cancel`,
|
|
363
|
+
/// the timeout, and teardown, so it is refused up front).
|
|
311
364
|
rejected,
|
|
312
365
|
/// DNS resolution or the TCP connect failed (unknown host,
|
|
313
366
|
/// connection refused, network unreachable).
|
|
@@ -436,6 +489,26 @@ pub const EffectClipboardResult = struct {
|
|
|
436
489
|
dropped_before: u32 = 0,
|
|
437
490
|
};
|
|
438
491
|
|
|
492
|
+
/// Payload for `on_result` Msg constructors of host requests
|
|
493
|
+
/// (`hostRequest` — the generic named host call behind transpiled
|
|
494
|
+
/// cores' `request` wire records). Exactly one terminal per request,
|
|
495
|
+
/// routed by `ok`: true is the success route with the result bytes,
|
|
496
|
+
/// false the error route with the error bytes. Unlike the other keyed
|
|
497
|
+
/// effects there is no outcome enum and no cancelled terminal — the
|
|
498
|
+
/// request contract is REPLACE on key reuse and SILENT drop on cancel,
|
|
499
|
+
/// so the only deliveries are the host's answer and the loud rejection
|
|
500
|
+
/// (`ok = false`, bytes `"rejected"`) for a request the channel refused
|
|
501
|
+
/// (over-bound payload, key collision with another effect kind, no
|
|
502
|
+
/// slot, no bound host service).
|
|
503
|
+
pub const EffectHostResult = struct {
|
|
504
|
+
key: u64,
|
|
505
|
+
/// True routes the request's ok arm; false its err arm.
|
|
506
|
+
ok: bool = true,
|
|
507
|
+
/// Result (or error) bytes; drain scratch — copy what the model
|
|
508
|
+
/// keeps.
|
|
509
|
+
bytes: []const u8 = "",
|
|
510
|
+
};
|
|
511
|
+
|
|
439
512
|
/// Maximum concurrently armed fx timers per app. Timers are their own
|
|
440
513
|
/// fixed table: they do NOT consume `max_effects` slots or worker
|
|
441
514
|
/// threads (a timer is a platform service arm, not a blocking effect),
|
|
@@ -579,6 +652,22 @@ pub const EffectResultKind = enum(u8) {
|
|
|
579
652
|
timer = 6,
|
|
580
653
|
clock = 7,
|
|
581
654
|
audio = 8,
|
|
655
|
+
/// A host-request terminal (`EffectHostResult`). Additive over the
|
|
656
|
+
/// v3 journal layout — no new record fields: the ok/err route rides
|
|
657
|
+
/// `code` (0 ok, 1 err) and a channel-refused rejection is marked
|
|
658
|
+
/// by `exit_reason == .rejected` (rejections regenerate from the
|
|
659
|
+
/// same deterministic validation under replay and are never fed).
|
|
660
|
+
host = 9,
|
|
661
|
+
/// One launch-environment delivery (the TS adapter's `envMsgs`
|
|
662
|
+
/// channel): journaled as the adapter dispatches each launch value,
|
|
663
|
+
/// so replay feeds the RECORDED values instead of re-reading the
|
|
664
|
+
/// replay launch's environment. Additive over the v3 journal layout
|
|
665
|
+
/// — no new record fields: the value rides `payload`, the target
|
|
666
|
+
/// Msg arm name rides `stderr_tail`, and `key` is the dispatch
|
|
667
|
+
/// index. Journals without env records (older recordings, or
|
|
668
|
+
/// launches with no variables set) re-derive from the launch
|
|
669
|
+
/// configuration exactly as before.
|
|
670
|
+
env = 10,
|
|
582
671
|
};
|
|
583
672
|
|
|
584
673
|
/// Journaled wall-clock reads buffered for replay (`Effects.wallMs`).
|
|
@@ -586,6 +675,19 @@ pub const EffectResultKind = enum(u8) {
|
|
|
586
675
|
/// is a runaway loop, not a session shape.
|
|
587
676
|
pub const max_effect_replay_clock_entries: usize = 64;
|
|
588
677
|
|
|
678
|
+
/// Journaled launch-env deliveries buffered for replay (the `.env`
|
|
679
|
+
/// record feed). Bounded like the clock queue: more launch variables
|
|
680
|
+
/// than this is a wiring bug, not a session shape.
|
|
681
|
+
pub const max_effect_replay_env_entries: usize = 32;
|
|
682
|
+
|
|
683
|
+
/// One queued launch-env delivery: the target Msg arm name and the
|
|
684
|
+
/// recorded value bytes (both reference the journal, which outlives the
|
|
685
|
+
/// replay).
|
|
686
|
+
pub const ReplayEnvEntry = struct {
|
|
687
|
+
msg: []const u8,
|
|
688
|
+
value: []const u8,
|
|
689
|
+
};
|
|
690
|
+
|
|
589
691
|
/// One drained effect result, flattened for the session journal: the
|
|
590
692
|
/// exact payload `update` received, Msg-type-erased so the recorder and
|
|
591
693
|
/// replayer need no knowledge of the app's Msg union. Only the fields
|
|
@@ -679,6 +781,90 @@ fn fallbackEnviron() std.process.Environ {
|
|
|
679
781
|
/// host, so nothing is lost.
|
|
680
782
|
const io_threaded_supported = builtin.target.os.tag != .freestanding;
|
|
681
783
|
const IoThreaded = if (io_threaded_supported) std.Io.Threaded else void;
|
|
784
|
+
/// Worker-thread handles exist only where the threaded executor does
|
|
785
|
+
/// (the same seam as `IoThreaded`): on freestanding targets no worker
|
|
786
|
+
/// ever spawns, so the slot field compiles away to a `?void`.
|
|
787
|
+
const WorkerThread = if (io_threaded_supported) std.Thread else void;
|
|
788
|
+
|
|
789
|
+
/// Process-lifetime allocator backing everything an ABANDONED file
|
|
790
|
+
/// worker can still reach: its `FileWorkerContext`, that context's
|
|
791
|
+
/// data buffer, and the shared executor io (`IoThreaded` and its
|
|
792
|
+
/// internals). The channel's own `allocator` is the OWNER's — an
|
|
793
|
+
/// arena or GPA typically deinitialized right after `Effects.deinit`
|
|
794
|
+
/// returns — so "leaking" caller-allocator memory under a live thread
|
|
795
|
+
/// would only reintroduce the use-after-free the abandon path exists
|
|
796
|
+
/// to prevent; abandonable memory must come from storage nothing ever
|
|
797
|
+
/// tears down. The page allocator is that storage: process-lived by
|
|
798
|
+
/// construction (it has no deinit), thread-safe, and available on
|
|
799
|
+
/// every target including the docs' wasm32-freestanding preview.
|
|
800
|
+
/// Page granularity is irrelevant here — file effects allocate one
|
|
801
|
+
/// small context and one bounded (~1 MiB) buffer per op, and the
|
|
802
|
+
/// executor io is created once, none of it on a hot path. The happy
|
|
803
|
+
/// path frees through this same allocator: `joinWorker` releases the
|
|
804
|
+
/// context and its buffer, `deinit` releases the executor io.
|
|
805
|
+
const process_allocator: std.mem.Allocator = std.heap.page_allocator;
|
|
806
|
+
|
|
807
|
+
/// Everything a real file worker's BLOCKING phase may touch, held
|
|
808
|
+
/// out-of-line from the channel on its own heap block. File I/O is the
|
|
809
|
+
/// one effect teardown cannot always interrupt (a write to a FIFO with
|
|
810
|
+
/// no reader, a stalled network filesystem), so `deinit` bounds its
|
|
811
|
+
/// wait and may ABANDON the worker: it detaches the thread and
|
|
812
|
+
/// deliberately leaks this context together with the buffer it points
|
|
813
|
+
/// at. The invariant that makes the leak safe: an abandoned worker may
|
|
814
|
+
/// wake at ANY later time, so everything it can still reach — this
|
|
815
|
+
/// context, `buffer`, and the executor io — lives in process-lifetime
|
|
816
|
+
/// storage (`process_allocator`, never the channel's caller-owned
|
|
817
|
+
/// allocator) and stays allocated forever, while everything it must
|
|
818
|
+
/// never touch again (the slot, the queue, the channel itself) is
|
|
819
|
+
/// fenced off by the commit/abandon handshake under `mutex`. The leak
|
|
820
|
+
/// is bounded (at most one context and buffer per file slot per
|
|
821
|
+
/// torn-down channel, plus the shared executor io) and loud (`deinit`
|
|
822
|
+
/// warns with the stuck op and path when it gives up).
|
|
823
|
+
const FileWorkerContext = struct {
|
|
824
|
+
/// Serializes the worker's commit-to-publish transition against
|
|
825
|
+
/// teardown's abandon decision: whoever locks first decides
|
|
826
|
+
/// whether the worker may still touch the channel (teardown
|
|
827
|
+
/// joins it) or must walk away (teardown leaks it).
|
|
828
|
+
mutex: SpinMutex = .{},
|
|
829
|
+
/// Teardown gave up on this worker: it must never touch the
|
|
830
|
+
/// channel again — the owner is about to free that memory.
|
|
831
|
+
abandoned: bool = false,
|
|
832
|
+
/// The worker finished its blocking phase while the channel was
|
|
833
|
+
/// still alive: teardown must join it (its epilogue touches the
|
|
834
|
+
/// slot and queue, and converges within milliseconds because the
|
|
835
|
+
/// terminal post gives up on shutdown).
|
|
836
|
+
committed: bool = false,
|
|
837
|
+
/// Set by `deinit` halfway through its file deadline: the
|
|
838
|
+
/// supervisor cancels the blocking task (best-effort syscall
|
|
839
|
+
/// interruption through the threaded io).
|
|
840
|
+
interrupt: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
|
|
841
|
+
/// Set by the task after `outcome`/`read_len` are recorded.
|
|
842
|
+
done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
|
|
843
|
+
op: EffectFileOp,
|
|
844
|
+
/// The worker's PRIVATE data buffer (a write's payload copy, a
|
|
845
|
+
/// read's content space) — its own `process_allocator` allocation,
|
|
846
|
+
/// distinct from the slot's caller-allocated delivery buffer,
|
|
847
|
+
/// leaked alongside this context on abandon and freed with it by
|
|
848
|
+
/// `joinWorker` otherwise. A committed read's bytes are copied
|
|
849
|
+
/// into the slot's delivery buffer by the worker epilogue.
|
|
850
|
+
buffer: []u8,
|
|
851
|
+
payload_len: usize,
|
|
852
|
+
read_len: usize = 0,
|
|
853
|
+
outcome: EffectFileOutcome = .io_failed,
|
|
854
|
+
/// Copy of the effect's path: the slot's copy lives inside the
|
|
855
|
+
/// channel, which the owner frees right after an abandoning
|
|
856
|
+
/// teardown returns.
|
|
857
|
+
path_storage: [max_effect_file_path_bytes]u8 = undefined,
|
|
858
|
+
path_len: usize = 0,
|
|
859
|
+
|
|
860
|
+
fn path(ctx: *const FileWorkerContext) []const u8 {
|
|
861
|
+
return ctx.path_storage[0..ctx.path_len];
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
fn payload(ctx: *const FileWorkerContext) []const u8 {
|
|
865
|
+
return ctx.buffer[0..ctx.payload_len];
|
|
866
|
+
}
|
|
867
|
+
};
|
|
682
868
|
|
|
683
869
|
/// Map a fetch-side error onto the delivered failure taxonomy. The
|
|
684
870
|
/// worker refines `.cancelled` into `.timed_out` when the deadline (not
|
|
@@ -732,6 +918,7 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
732
918
|
pub const ClipboardMsgFn = *const fn (result: EffectClipboardResult) Msg;
|
|
733
919
|
pub const TimerMsgFn = *const fn (timer: EffectTimer) Msg;
|
|
734
920
|
pub const AudioMsgFn = *const fn (event: EffectAudio) Msg;
|
|
921
|
+
pub const HostMsgFn = *const fn (result: EffectHostResult) Msg;
|
|
735
922
|
|
|
736
923
|
/// Comptime Msg constructor for `on_line`, following
|
|
737
924
|
/// `canvas.Ui(Msg).inputMsg`: `lineMsg(.agent_line)` builds
|
|
@@ -816,6 +1003,18 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
816
1003
|
}.make;
|
|
817
1004
|
}
|
|
818
1005
|
|
|
1006
|
+
/// Comptime Msg constructor for `on_result` of host requests:
|
|
1007
|
+
/// `hostMsg(.store_answered)` builds
|
|
1008
|
+
/// `Msg{ .store_answered = result }` — the variant's payload
|
|
1009
|
+
/// type must be `native_sdk.EffectHostResult`.
|
|
1010
|
+
pub fn hostMsg(comptime tag: std.meta.Tag(Msg)) HostMsgFn {
|
|
1011
|
+
return struct {
|
|
1012
|
+
fn make(result: EffectHostResult) Msg {
|
|
1013
|
+
return @unionInit(Msg, @tagName(tag), result);
|
|
1014
|
+
}
|
|
1015
|
+
}.make;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
819
1018
|
pub const SpawnOptions = struct {
|
|
820
1019
|
/// Caller-chosen identity, stored in the model. Must not
|
|
821
1020
|
/// collide with another still-running effect.
|
|
@@ -974,6 +1173,32 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
974
1173
|
text: []const u8 = "",
|
|
975
1174
|
};
|
|
976
1175
|
|
|
1176
|
+
pub const HostRequestOptions = struct {
|
|
1177
|
+
/// Caller-chosen identity. Same key space and slots as
|
|
1178
|
+
/// spawn/fetch/file/clipboard, but with the request key
|
|
1179
|
+
/// discipline: issuing a key whose HOST request is still in
|
|
1180
|
+
/// flight REPLACES it (the old result is dropped, silently),
|
|
1181
|
+
/// while a collision with another effect kind rejects.
|
|
1182
|
+
key: u64,
|
|
1183
|
+
/// Host service name (what the host dispatches on), at most
|
|
1184
|
+
/// `max_effect_host_name_bytes`; copied into slot storage.
|
|
1185
|
+
name: []const u8,
|
|
1186
|
+
/// Outbound payload, at most
|
|
1187
|
+
/// `max_effect_host_payload_bytes`; copied into the slot's
|
|
1188
|
+
/// buffer at call time.
|
|
1189
|
+
payload: []const u8 = "",
|
|
1190
|
+
on_result: ?HostMsgFn = null,
|
|
1191
|
+
};
|
|
1192
|
+
|
|
1193
|
+
/// A recorded host request, exposed by the fake executor for
|
|
1194
|
+
/// test assertions. Slices point into slot storage and stay
|
|
1195
|
+
/// valid until the request retires.
|
|
1196
|
+
pub const HostRequest = struct {
|
|
1197
|
+
key: u64,
|
|
1198
|
+
name: []const u8,
|
|
1199
|
+
payload: []const u8 = "",
|
|
1200
|
+
};
|
|
1201
|
+
|
|
977
1202
|
pub const StartTimerOptions = struct {
|
|
978
1203
|
/// Caller-chosen identity, stored in the model. Timer keys
|
|
979
1204
|
/// are their own namespace: they never collide with (and are
|
|
@@ -1139,9 +1364,9 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1139
1364
|
/// thereby retires) it.
|
|
1140
1365
|
const SlotState = enum(u8) { idle, running, done, draining };
|
|
1141
1366
|
|
|
1142
|
-
const SlotKind = enum(u8) { spawn, fetch, file, clipboard };
|
|
1367
|
+
const SlotKind = enum(u8) { spawn, fetch, file, clipboard, host };
|
|
1143
1368
|
|
|
1144
|
-
const EntryKind = enum(u8) { line, exit, response, file, clipboard };
|
|
1369
|
+
const EntryKind = enum(u8) { line, exit, response, file, clipboard, host };
|
|
1145
1370
|
|
|
1146
1371
|
const Entry = struct {
|
|
1147
1372
|
kind: EntryKind = .line,
|
|
@@ -1171,6 +1396,11 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1171
1396
|
/// `line_len`.
|
|
1172
1397
|
clipboard_op: EffectClipboardOp = .write,
|
|
1173
1398
|
clipboard_outcome: EffectClipboardOutcome = .ok,
|
|
1399
|
+
/// `.host` entries: which route the result takes (true = the
|
|
1400
|
+
/// ok arm). The bytes stay in the slot's heap buffer (taken
|
|
1401
|
+
/// at drain, like a fetch body) with their length in
|
|
1402
|
+
/// `line_len`.
|
|
1403
|
+
host_ok: bool = true,
|
|
1174
1404
|
/// `.exit` entries of `.collect` spawns: the collected stdout
|
|
1175
1405
|
/// stays in the slot's heap buffer (taken at drain, like a
|
|
1176
1406
|
/// fetch body); the stderr tail rides in `line_bytes` with
|
|
@@ -1184,6 +1414,7 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1184
1414
|
response_fn: ?ResponseMsgFn = null,
|
|
1185
1415
|
file_fn: ?FileMsgFn = null,
|
|
1186
1416
|
clipboard_fn: ?ClipboardMsgFn = null,
|
|
1417
|
+
host_fn: ?HostMsgFn = null,
|
|
1187
1418
|
/// `.line` entries whose payload exceeds the inline buffer
|
|
1188
1419
|
/// (a raised `max_line_bytes` bound): the bytes ride in this
|
|
1189
1420
|
/// heap allocation instead of `line_bytes`. Owned by the
|
|
@@ -1202,6 +1433,11 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1202
1433
|
file: struct { result: EffectFileResult, file_fn: ?FileMsgFn },
|
|
1203
1434
|
clipboard: struct { result: EffectClipboardResult, clipboard_fn: ?ClipboardMsgFn },
|
|
1204
1435
|
timer: struct { timer: EffectTimer, timer_fn: ?TimerMsgFn },
|
|
1436
|
+
/// `.host` terminals produced on the loop thread: rejections
|
|
1437
|
+
/// (`rejected = true`, static bytes, regenerated under
|
|
1438
|
+
/// replay) and feed fallbacks. Bytes here are never a host
|
|
1439
|
+
/// answer's — those ride the queue with their slot buffer.
|
|
1440
|
+
host: struct { result: EffectHostResult, host_fn: ?HostMsgFn, rejected: bool },
|
|
1205
1441
|
/// `resolve`: a fed audio event (fake executor / replay)
|
|
1206
1442
|
/// whose key and handler come from the live channel at
|
|
1207
1443
|
/// delivery time — exactly how a platform event resolves in
|
|
@@ -1221,6 +1457,9 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1221
1457
|
// EffectAudio carries no drop counter either; the
|
|
1222
1458
|
// next position tick supersedes a lost one.
|
|
1223
1459
|
.audio => {},
|
|
1460
|
+
// EffectHostResult carries none: its terminals are
|
|
1461
|
+
// one-per-request by construction.
|
|
1462
|
+
.host => {},
|
|
1224
1463
|
}
|
|
1225
1464
|
}
|
|
1226
1465
|
|
|
@@ -1232,10 +1471,120 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1232
1471
|
.clipboard => |entry| entry.result.dropped_before,
|
|
1233
1472
|
.timer => 0,
|
|
1234
1473
|
.audio => 0,
|
|
1474
|
+
.host => 0,
|
|
1235
1475
|
};
|
|
1236
1476
|
}
|
|
1237
1477
|
};
|
|
1238
1478
|
|
|
1479
|
+
/// Everything a real spawn worker's BLOCKING phase may touch,
|
|
1480
|
+
/// held out-of-line from the channel on its own heap block —
|
|
1481
|
+
/// the spawn twin of `FileWorkerContext`, and the same
|
|
1482
|
+
/// invariant: teardown may ABANDON a spawn worker whose child's
|
|
1483
|
+
/// group-kill did not converge it (a descendant that escaped
|
|
1484
|
+
/// the process group — `setsid`, a shell's `set -m` background
|
|
1485
|
+
/// job — keeps the inherited stdout write end open, so the
|
|
1486
|
+
/// worker's read never sees EOF), and everything the abandoned
|
|
1487
|
+
/// worker can still wake into must live in process-lifetime
|
|
1488
|
+
/// storage (`process_allocator`) and stay allocated forever.
|
|
1489
|
+
/// The blocking phase therefore runs against copies: argv,
|
|
1490
|
+
/// stdin, the line-framing and collect buffers, the stderr
|
|
1491
|
+
/// tail ring, and the published-child handshake all live here,
|
|
1492
|
+
/// never in the slot. Unlike a file op, a spawn DELIVERS while
|
|
1493
|
+
/// it blocks (streaming lines ride the queue as the child
|
|
1494
|
+
/// produces them), so the commit/abandon handshake fences two
|
|
1495
|
+
/// things: every mid-stream channel touch happens under
|
|
1496
|
+
/// `mutex` with `abandoned` re-checked (see
|
|
1497
|
+
/// `produceSpawnLine`), and the terminal epilogue (publishing
|
|
1498
|
+
/// collect payloads into the slot, posting the exit) runs only
|
|
1499
|
+
/// after `committed` is taken while the channel provably
|
|
1500
|
+
/// lives. Generic over the channel because it carries the
|
|
1501
|
+
/// effect's Msg-typed `on_line` constructor.
|
|
1502
|
+
const SpawnWorkerContext = struct {
|
|
1503
|
+
/// Serializes the worker's channel touches (mid-stream
|
|
1504
|
+
/// line enqueues, the commit-to-publish transition)
|
|
1505
|
+
/// against teardown's abandon decision: whoever locks
|
|
1506
|
+
/// first decides whether the worker may still touch the
|
|
1507
|
+
/// channel (teardown joins it) or must walk away
|
|
1508
|
+
/// (teardown leaks it).
|
|
1509
|
+
mutex: SpinMutex = .{},
|
|
1510
|
+
/// Teardown gave up on this worker: it must never touch
|
|
1511
|
+
/// the channel again — the owner is about to free that
|
|
1512
|
+
/// memory.
|
|
1513
|
+
abandoned: bool = false,
|
|
1514
|
+
/// The worker finished its blocking phase while the
|
|
1515
|
+
/// channel was still alive: teardown must join it (its
|
|
1516
|
+
/// epilogue touches the slot and queue, and converges
|
|
1517
|
+
/// within milliseconds because the terminal post gives up
|
|
1518
|
+
/// on shutdown).
|
|
1519
|
+
committed: bool = false,
|
|
1520
|
+
/// Set by `deinit` halfway through its spawn deadline:
|
|
1521
|
+
/// the supervisor cancels the blocking task (best-effort
|
|
1522
|
+
/// syscall interruption through the threaded io — the net
|
|
1523
|
+
/// under a group-kill that could not converge the child).
|
|
1524
|
+
interrupt: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
|
|
1525
|
+
/// Set by the task after `exit` is recorded.
|
|
1526
|
+
done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
|
|
1527
|
+
/// Guards `child_id`/`reaping` between the blocking task
|
|
1528
|
+
/// and `killPublishedChild` (cancel on the loop thread,
|
|
1529
|
+
/// teardown): a kill is only sent while the task has not
|
|
1530
|
+
/// started reaping, so the pid/handle is guaranteed
|
|
1531
|
+
/// un-reaped (alive or zombie) when signaled. Lives here —
|
|
1532
|
+
/// not on the slot — so the handshake works against
|
|
1533
|
+
/// process-lived memory: the task locks it mid-blocking-
|
|
1534
|
+
/// phase, which an abandoned worker may do long after the
|
|
1535
|
+
/// channel is freed (the exact stale-slot `child_mutex`
|
|
1536
|
+
/// crash the join discipline exists to prevent).
|
|
1537
|
+
child_mutex: SpinMutex = .{},
|
|
1538
|
+
child_id: ?std.process.Child.Id = null,
|
|
1539
|
+
reaping: bool = false,
|
|
1540
|
+
/// A kill was requested (cancel or teardown). Read by the
|
|
1541
|
+
/// task so a kill that raced the child's publish still
|
|
1542
|
+
/// lands, and so the recorded exit reports `.cancelled` —
|
|
1543
|
+
/// the context's copy of the slot's `cancel_requested`,
|
|
1544
|
+
/// readable without touching the channel.
|
|
1545
|
+
kill_requested: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
|
|
1546
|
+
/// The task's terminal result, published to the committed
|
|
1547
|
+
/// epilogue (never read on abandon).
|
|
1548
|
+
exit: EffectExit = .{ .key = 0, .code = effect_error_exit_code, .reason = .spawn_failed },
|
|
1549
|
+
// ---- blocking-phase copies of the effect's parameters ----
|
|
1550
|
+
key: u64 = 0,
|
|
1551
|
+
on_line: ?LineMsgFn = null,
|
|
1552
|
+
output_mode: EffectOutputMode = .lines,
|
|
1553
|
+
line_limit: usize = max_effect_line_bytes,
|
|
1554
|
+
/// Raised-bound line-framing buffer (its own
|
|
1555
|
+
/// `process_allocator` allocation, leaked on abandon,
|
|
1556
|
+
/// freed with the context by `joinWorker`); null means the
|
|
1557
|
+
/// task frames into its stack buffer. Distinct from the
|
|
1558
|
+
/// slot's `line_buffer`, which the fake executor keeps
|
|
1559
|
+
/// using.
|
|
1560
|
+
line_buffer: ?[]u8 = null,
|
|
1561
|
+
/// Collect-mode stdout accumulation — the worker-private
|
|
1562
|
+
/// twin of the slot's caller-allocated `collect_buffer`
|
|
1563
|
+
/// (the committed epilogue publishes into that one).
|
|
1564
|
+
collect_buffer: ?[]u8 = null,
|
|
1565
|
+
collect_len: usize = 0,
|
|
1566
|
+
collect_truncated: bool = false,
|
|
1567
|
+
stderr_ring: [max_effect_stderr_tail_bytes]u8 = undefined,
|
|
1568
|
+
stderr_total: usize = 0,
|
|
1569
|
+
/// Producer-side drop accounting (the context twin of the
|
|
1570
|
+
/// slot fields the fake executor uses).
|
|
1571
|
+
dropped_pending: u32 = 0,
|
|
1572
|
+
dropped_total: u32 = 0,
|
|
1573
|
+
argv_slices: [max_effect_argv][]const u8 = undefined,
|
|
1574
|
+
argv_count: usize = 0,
|
|
1575
|
+
argv_storage: [max_effect_argv_bytes]u8 = undefined,
|
|
1576
|
+
stdin_storage: [max_effect_stdin_bytes]u8 = undefined,
|
|
1577
|
+
stdin_len: usize = 0,
|
|
1578
|
+
|
|
1579
|
+
fn argv(ctx: *const SpawnWorkerContext) []const []const u8 {
|
|
1580
|
+
return ctx.argv_slices[0..ctx.argv_count];
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
fn stdinBytes(ctx: *const SpawnWorkerContext) []const u8 {
|
|
1584
|
+
return ctx.stdin_storage[0..ctx.stdin_len];
|
|
1585
|
+
}
|
|
1586
|
+
};
|
|
1587
|
+
|
|
1239
1588
|
const Slot = struct {
|
|
1240
1589
|
state: std.atomic.Value(SlotState) = std.atomic.Value(SlotState).init(.idle),
|
|
1241
1590
|
generation: u32 = 0,
|
|
@@ -1247,6 +1596,7 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1247
1596
|
on_response: ?ResponseMsgFn = null,
|
|
1248
1597
|
on_file: ?FileMsgFn = null,
|
|
1249
1598
|
on_clipboard: ?ClipboardMsgFn = null,
|
|
1599
|
+
on_host: ?HostMsgFn = null,
|
|
1250
1600
|
/// Set by `cancel` before any kill attempt; read by the
|
|
1251
1601
|
/// worker so a cancel that lands before the process spawns
|
|
1252
1602
|
/// still kills it.
|
|
@@ -1255,13 +1605,34 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1255
1605
|
/// lines the drain discards and whose exit reports
|
|
1256
1606
|
/// `.cancelled`. Zero means none (generations start at 1).
|
|
1257
1607
|
cancelled_generation: u32 = 0,
|
|
1258
|
-
///
|
|
1259
|
-
///
|
|
1260
|
-
///
|
|
1261
|
-
///
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1608
|
+
/// The worker thread driving this occupancy (real spawn,
|
|
1609
|
+
/// fetch, and file effects; null for fake slots, host
|
|
1610
|
+
/// requests, and idle slots). Loop-thread bookkeeping:
|
|
1611
|
+
/// stored where the thread spawns, cleared by `joinWorker`.
|
|
1612
|
+
/// A worker holds pointers into the whole channel (its
|
|
1613
|
+
/// slot, the completion queue, the executor io) for its
|
|
1614
|
+
/// entire thread lifetime, so the channel's memory must
|
|
1615
|
+
/// never be freed while a handle here is outstanding —
|
|
1616
|
+
/// `deinit` joins every one before it returns, except a
|
|
1617
|
+
/// file or spawn worker stuck past its teardown deadline,
|
|
1618
|
+
/// which is detached after the handshake that guarantees
|
|
1619
|
+
/// it will never touch the channel again (see
|
|
1620
|
+
/// `FileWorkerContext` / `SpawnWorkerContext`).
|
|
1621
|
+
worker_thread: ?WorkerThread = null,
|
|
1622
|
+
/// The out-of-line world of a real file worker (null for
|
|
1623
|
+
/// every other occupancy). Created alongside the worker
|
|
1624
|
+
/// thread, freed by `joinWorker` once the join proves the
|
|
1625
|
+
/// worker is gone — or deliberately leaked when teardown
|
|
1626
|
+
/// abandons the worker (see `FileWorkerContext`).
|
|
1627
|
+
file_ctx: ?*FileWorkerContext = null,
|
|
1628
|
+
/// The out-of-line world of a real spawn worker (null for
|
|
1629
|
+
/// every other occupancy, and for fake spawns). Same
|
|
1630
|
+
/// lifecycle as `file_ctx`: freed by `joinWorker`, leaked
|
|
1631
|
+
/// on abandon (see `SpawnWorkerContext`). Also where
|
|
1632
|
+
/// `killPublishedChild` finds the published-child
|
|
1633
|
+
/// handshake — the loop thread only dereferences it while
|
|
1634
|
+
/// the channel is alive.
|
|
1635
|
+
spawn_ctx: ?*SpawnWorkerContext = null,
|
|
1265
1636
|
/// Producer-side drop accounting (worker in real mode, loop
|
|
1266
1637
|
/// thread in fake mode; never both).
|
|
1267
1638
|
dropped_pending: u32 = 0,
|
|
@@ -1357,6 +1728,12 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1357
1728
|
fn filePath(slot: *const Slot) []const u8 {
|
|
1358
1729
|
return slot.url_storage[0..slot.url_len];
|
|
1359
1730
|
}
|
|
1731
|
+
|
|
1732
|
+
/// A host request's service name (they share the fetch URL
|
|
1733
|
+
/// storage — a slot is one occupancy at a time).
|
|
1734
|
+
fn hostName(slot: *const Slot) []const u8 {
|
|
1735
|
+
return slot.url_storage[0..slot.url_len];
|
|
1736
|
+
}
|
|
1360
1737
|
};
|
|
1361
1738
|
|
|
1362
1739
|
allocator: std.mem.Allocator,
|
|
@@ -1386,6 +1763,14 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1386
1763
|
/// divergence signal (the replayed update read the clock more
|
|
1387
1764
|
/// often than the recorded one). Reported loudly once.
|
|
1388
1765
|
replay_clock_underflows: u64 = 0,
|
|
1766
|
+
/// Journaled launch-env deliveries queued for the replay-mode
|
|
1767
|
+
/// envMsgs dispatch (FIFO; fed from `.env` records before the
|
|
1768
|
+
/// installing event dispatches). Empty under replay means the
|
|
1769
|
+
/// journal carried none — the adapter re-derives from the
|
|
1770
|
+
/// launch configuration, the pre-`.env`-record behavior.
|
|
1771
|
+
replay_env: [max_effect_replay_env_entries]ReplayEnvEntry = undefined,
|
|
1772
|
+
replay_env_head: usize = 0,
|
|
1773
|
+
replay_env_len: usize = 0,
|
|
1389
1774
|
/// Set once from the loop thread before the first dispatch;
|
|
1390
1775
|
/// workers call `services.wake()` through it (the one
|
|
1391
1776
|
/// thread-safe PlatformServices entry).
|
|
@@ -1398,6 +1783,12 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1398
1783
|
/// by `UiApp` alongside the services — the seam behind
|
|
1399
1784
|
/// app-drawn window controls (loop-thread only).
|
|
1400
1785
|
window_actions: ?WindowActionBinding = null,
|
|
1786
|
+
/// The embedding host's named-command services (`hostSend` /
|
|
1787
|
+
/// `hostRequest`), bound by whoever hosts a transpiled app core
|
|
1788
|
+
/// (loop-thread only). Null means no host services: sends drop,
|
|
1789
|
+
/// requests reject loudly in real mode, and the fake executor
|
|
1790
|
+
/// parks requests for `feedHostResult` regardless.
|
|
1791
|
+
host_calls: ?HostCallBinding = null,
|
|
1401
1792
|
/// Window-action mirror: counts and the last requested label,
|
|
1402
1793
|
/// observable in tests (`windowActionState`).
|
|
1403
1794
|
window_action_state: WindowActionState = .{},
|
|
@@ -1409,6 +1800,59 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1409
1800
|
environ: ?std.process.Environ = null,
|
|
1410
1801
|
io_threaded: ?*IoThreaded = null,
|
|
1411
1802
|
shutdown: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
|
|
1803
|
+
/// Teardown budget (total milliseconds) for file workers stuck
|
|
1804
|
+
/// in blocking I/O that nothing can force to converge; see
|
|
1805
|
+
/// `deinit` and `default_effect_file_join_deadline_ms`.
|
|
1806
|
+
/// Injectable so tests pin the interrupt and abandon paths
|
|
1807
|
+
/// with a tiny bound.
|
|
1808
|
+
file_join_deadline_ms: u64 = default_effect_file_join_deadline_ms,
|
|
1809
|
+
/// Best-effort interruption switch: halfway through the file
|
|
1810
|
+
/// deadline, teardown cancels a stuck file worker's blocking
|
|
1811
|
+
/// task (the threaded io interrupts the blocked syscall —
|
|
1812
|
+
/// pthread_kill(SIG.IO)/tgkill on POSIX,
|
|
1813
|
+
/// NtCancelSynchronousIoFile on Windows). Always true in real
|
|
1814
|
+
/// use; tests disable it to reach the abandon-and-leak safety
|
|
1815
|
+
/// net deterministically.
|
|
1816
|
+
file_join_interrupt: bool = true,
|
|
1817
|
+
/// How many file workers teardown has abandoned (each one a
|
|
1818
|
+
/// bounded, warned leak — see `FileWorkerContext`). The seam
|
|
1819
|
+
/// tests assert against: zero on every healthy teardown.
|
|
1820
|
+
abandoned_file_workers: u32 = 0,
|
|
1821
|
+
/// Teardown budget (total milliseconds) for spawn workers the
|
|
1822
|
+
/// group-kill could not converge — a descendant that escaped
|
|
1823
|
+
/// the child's process group (`setsid`, a shell's `set -m`
|
|
1824
|
+
/// background job) keeps the inherited stdout write end open,
|
|
1825
|
+
/// so the worker's read never sees EOF. Shares the file
|
|
1826
|
+
/// deadline's default deliberately (the rationale is
|
|
1827
|
+
/// identical: generous, and a healthy teardown — the kill
|
|
1828
|
+
/// forcing EOF within milliseconds — never meets it) but stays
|
|
1829
|
+
/// its own field so tests pin each worker class independently.
|
|
1830
|
+
spawn_join_deadline_ms: u64 = default_effect_file_join_deadline_ms,
|
|
1831
|
+
/// Best-effort interruption switch for spawn workers,
|
|
1832
|
+
/// mirroring `file_join_interrupt`: halfway through the spawn
|
|
1833
|
+
/// deadline, teardown cancels a stuck worker's blocking task
|
|
1834
|
+
/// (the threaded io interrupts the blocked pipe read). Always
|
|
1835
|
+
/// true in real use; tests disable it to reach the
|
|
1836
|
+
/// abandon-and-leak safety net deterministically.
|
|
1837
|
+
spawn_join_interrupt: bool = true,
|
|
1838
|
+
/// How many spawn workers teardown has abandoned (each one a
|
|
1839
|
+
/// bounded, warned leak — see `SpawnWorkerContext`). The seam
|
|
1840
|
+
/// tests assert against: zero on every healthy teardown.
|
|
1841
|
+
abandoned_spawn_workers: u32 = 0,
|
|
1842
|
+
/// Injectable concurrent-start switch for fetch supervisors,
|
|
1843
|
+
/// following `file_join_interrupt`: always true in real use;
|
|
1844
|
+
/// tests disable it to pin the no-capacity rejection path
|
|
1845
|
+
/// deterministically (the real trigger — the executor refusing
|
|
1846
|
+
/// `std.Io.concurrent` — needs resource exhaustion). See
|
|
1847
|
+
/// `fetchWorkerMain`.
|
|
1848
|
+
fetch_concurrent_start: bool = true,
|
|
1849
|
+
/// How many fetches were REFUSED because the executor could
|
|
1850
|
+
/// not start their exchange as a cancelable task (each one a
|
|
1851
|
+
/// `.rejected` terminal and a one-time warning — never an
|
|
1852
|
+
/// uncancelable inline exchange). Incremented by worker
|
|
1853
|
+
/// threads; read it from the loop thread after the terminal
|
|
1854
|
+
/// drained.
|
|
1855
|
+
fetch_start_rejections: std.atomic.Value(u32) = std.atomic.Value(u32).init(0),
|
|
1412
1856
|
next_generation: u32 = 1,
|
|
1413
1857
|
slots: [max_effects]Slot = [_]Slot{.{}} ** max_effects,
|
|
1414
1858
|
/// Fixed fx timer table (see `max_effect_timers`): timers live
|
|
@@ -1453,8 +1897,32 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1453
1897
|
}
|
|
1454
1898
|
|
|
1455
1899
|
/// Kill every running effect, wait for the workers to finish
|
|
1456
|
-
/// (draining their final queue posts),
|
|
1457
|
-
///
|
|
1900
|
+
/// (draining their final queue posts), JOIN every worker
|
|
1901
|
+
/// thread, and release the executor io. Fetch joins are
|
|
1902
|
+
/// unconditional — fetch supervisors cancel on the shutdown
|
|
1903
|
+
/// flag (and an exchange that cannot start cancellably is
|
|
1904
|
+
/// rejected up front), so no fetch worker survives this call.
|
|
1905
|
+
/// Spawn and file workers get a deadline each
|
|
1906
|
+
/// (`spawn_join_deadline_ms` / `file_join_deadline_ms`), with
|
|
1907
|
+
/// a best-effort cancel of the blocked task at the halfway
|
|
1908
|
+
/// mark: a spawn normally converges from the process-group
|
|
1909
|
+
/// kill within milliseconds, but a descendant that escaped the
|
|
1910
|
+
/// group (`setsid`, a shell's `set -m` background job) keeps
|
|
1911
|
+
/// the stdout pipe open past every kill, and file I/O has no
|
|
1912
|
+
/// converging force at all (a write to a FIFO with no reader,
|
|
1913
|
+
/// a stalled network filesystem). A worker still stuck when
|
|
1914
|
+
/// its budget expires is ABANDONED — thread detached, its
|
|
1915
|
+
/// out-of-line context, private buffers, and the executor io
|
|
1916
|
+
/// deliberately leaked, one warning naming the stuck op (see
|
|
1917
|
+
/// `FileWorkerContext` / `SpawnWorkerContext` for the
|
|
1918
|
+
/// invariant). Either way the owner may free the channel's
|
|
1919
|
+
/// memory — and tear down the allocator behind it — the moment
|
|
1920
|
+
/// this returns: nothing an abandoned worker can still reach
|
|
1921
|
+
/// lives in the channel or in caller-allocator storage (the
|
|
1922
|
+
/// leakable set is allocated from `process_allocator`). All
|
|
1923
|
+
/// three worker classes share one terminal guarantee: teardown
|
|
1924
|
+
/// returns bounded, and every byte a live thread can still
|
|
1925
|
+
/// touch stays valid forever.
|
|
1458
1926
|
///
|
|
1459
1927
|
/// Idempotent, and only the FIRST call may touch platform
|
|
1460
1928
|
/// services — it ends by severing the services binding, so a
|
|
@@ -1482,6 +1950,16 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1482
1950
|
if (self.services) |services| services.audioStop() catch {};
|
|
1483
1951
|
}
|
|
1484
1952
|
self.audio = .{};
|
|
1953
|
+
// Host requests park on the loop thread with no worker to
|
|
1954
|
+
// wait for: retire them here so the worker wait below never
|
|
1955
|
+
// stalls on one, and any late host answer reports
|
|
1956
|
+
// EffectNotFound instead of touching a freed buffer.
|
|
1957
|
+
for (&self.slots) |*slot| {
|
|
1958
|
+
if (slot.kind == .host and slot.state.load(.acquire) == .running) {
|
|
1959
|
+
self.releaseFetchSlot(slot);
|
|
1960
|
+
slot.generation = 0;
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1485
1963
|
for (&self.slots) |*slot| {
|
|
1486
1964
|
if (slot.state.load(.acquire) == .running and !slot.fake) {
|
|
1487
1965
|
slot.cancel_requested.store(true, .release);
|
|
@@ -1492,22 +1970,186 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1492
1970
|
}
|
|
1493
1971
|
if (io_threaded_supported) {
|
|
1494
1972
|
if (self.io_threaded) |threaded| {
|
|
1973
|
+
// Wait for every worker's terminal post, then JOIN
|
|
1974
|
+
// every worker thread. For fetch workers the wait
|
|
1975
|
+
// is unbounded on purpose: a worker holds pointers
|
|
1976
|
+
// into this struct (its slot, the completion
|
|
1977
|
+
// queue, this io) for its whole thread lifetime,
|
|
1978
|
+
// and the owner frees this memory right after
|
|
1979
|
+
// deinit returns — a bounded give-up here once
|
|
1980
|
+
// left an abandoned worker writing into freed
|
|
1981
|
+
// memory, which is exactly how a torn-down app
|
|
1982
|
+
// crashed inside a stale slot's `child_mutex`.
|
|
1983
|
+
// Fetch convergence is the shutdown flag's doing:
|
|
1984
|
+
// supervisors poll it and cancel their exchange
|
|
1985
|
+
// (one that cannot start cancellably is rejected
|
|
1986
|
+
// up front, never run inline), and the
|
|
1987
|
+
// terminal-post retry loops give up on `shutdown`
|
|
1988
|
+
// within a millisecond. Spawn and file workers get
|
|
1989
|
+
// a deadline each instead, because their blocking
|
|
1990
|
+
// phase can outlive every converging force: the
|
|
1991
|
+
// group-kill above forces most spawn reads to EOF
|
|
1992
|
+
// within milliseconds (`child.wait` then reaps a
|
|
1993
|
+
// dead process, and a raced pre-publish cancel is
|
|
1994
|
+
// re-checked by the task itself), but a descendant
|
|
1995
|
+
// that escaped the process group keeps the pipe
|
|
1996
|
+
// open past every kill; file I/O has nothing to
|
|
1997
|
+
// kill at all. Halfway through each deadline the
|
|
1998
|
+
// supervisor is asked to cancel the blocked task
|
|
1999
|
+
// (the threaded io interrupts blocked syscalls
|
|
2000
|
+
// with a no-op signal on POSIX and
|
|
2001
|
+
// NtCancelSynchronousIoFile on Windows), and a
|
|
2002
|
+
// worker still stuck at the end is abandoned below
|
|
2003
|
+
// instead of hanging teardown forever. The queue
|
|
2004
|
+
// is still drained while waiting so posts that
|
|
2005
|
+
// landed before the flag retire promptly.
|
|
1495
2006
|
const io = threaded.io();
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
2007
|
+
const file_deadline_ms = self.file_join_deadline_ms;
|
|
2008
|
+
const spawn_deadline_ms = self.spawn_join_deadline_ms;
|
|
2009
|
+
var waited_ms: u64 = 0;
|
|
2010
|
+
var file_interrupt_sent = false;
|
|
2011
|
+
var spawn_interrupt_sent = false;
|
|
2012
|
+
while (true) {
|
|
2013
|
+
var converging = false;
|
|
2014
|
+
var file_pending = false;
|
|
2015
|
+
var spawn_pending = false;
|
|
1499
2016
|
for (&self.slots) |*slot| {
|
|
1500
|
-
if (slot.state.load(.acquire)
|
|
2017
|
+
if (slot.fake or slot.state.load(.acquire) != .running) continue;
|
|
2018
|
+
switch (slot.kind) {
|
|
2019
|
+
.file => file_pending = true,
|
|
2020
|
+
.spawn => spawn_pending = true,
|
|
2021
|
+
else => converging = true,
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
if (!converging and
|
|
2025
|
+
(!file_pending or waited_ms >= file_deadline_ms) and
|
|
2026
|
+
(!spawn_pending or waited_ms >= spawn_deadline_ms)) break;
|
|
2027
|
+
if (file_pending and !file_interrupt_sent and self.file_join_interrupt and waited_ms >= file_deadline_ms / 2) {
|
|
2028
|
+
file_interrupt_sent = true;
|
|
2029
|
+
for (&self.slots) |*slot| {
|
|
2030
|
+
if (slot.kind != .file or slot.fake) continue;
|
|
2031
|
+
if (slot.state.load(.acquire) != .running) continue;
|
|
2032
|
+
if (slot.file_ctx) |ctx| ctx.interrupt.store(true, .release);
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
if (spawn_pending and !spawn_interrupt_sent and self.spawn_join_interrupt and waited_ms >= spawn_deadline_ms / 2) {
|
|
2036
|
+
spawn_interrupt_sent = true;
|
|
2037
|
+
for (&self.slots) |*slot| {
|
|
2038
|
+
if (slot.kind != .spawn or slot.fake) continue;
|
|
2039
|
+
if (slot.state.load(.acquire) != .running) continue;
|
|
2040
|
+
if (slot.spawn_ctx) |ctx| ctx.interrupt.store(true, .release);
|
|
2041
|
+
}
|
|
1501
2042
|
}
|
|
1502
|
-
if (!running) break;
|
|
1503
|
-
// Keep the queue drained so exit-post retries finish.
|
|
1504
2043
|
self.clearQueue();
|
|
1505
2044
|
std.Io.sleep(io, std.Io.Duration.fromMilliseconds(1), .awake) catch break;
|
|
2045
|
+
waited_ms += 1;
|
|
2046
|
+
}
|
|
2047
|
+
var abandoned_any = false;
|
|
2048
|
+
for (&self.slots) |*slot| {
|
|
2049
|
+
if (slot.kind != .file or slot.fake) continue;
|
|
2050
|
+
if (slot.state.load(.acquire) != .running) continue;
|
|
2051
|
+
const ctx = slot.file_ctx orelse continue;
|
|
2052
|
+
// The commit/abandon handshake: whoever locks
|
|
2053
|
+
// first decides. A worker that just finished
|
|
2054
|
+
// has committed — it is touching the slot and
|
|
2055
|
+
// queue right now and converges in
|
|
2056
|
+
// milliseconds, so the unconditional join
|
|
2057
|
+
// below collects it like any other worker.
|
|
2058
|
+
ctx.mutex.lock();
|
|
2059
|
+
const committed = ctx.committed;
|
|
2060
|
+
if (!committed) ctx.abandoned = true;
|
|
2061
|
+
ctx.mutex.unlock();
|
|
2062
|
+
if (committed) continue;
|
|
2063
|
+
std.debug.print(
|
|
2064
|
+
"effects teardown: a file {s} against '{s}' is still blocked in I/O after {d}ms; abandoning its worker thread and leaking its buffers so teardown can return safely\n",
|
|
2065
|
+
.{ @tagName(slot.file_op), slot.filePath(), file_deadline_ms },
|
|
2066
|
+
);
|
|
2067
|
+
// DELIBERATE LEAK — the invariant that makes it
|
|
2068
|
+
// safe: the abandoned worker may wake at any
|
|
2069
|
+
// later time, so everything it can still reach
|
|
2070
|
+
// must stay allocated forever — its context
|
|
2071
|
+
// (`ctx`, dropped here without freeing), that
|
|
2072
|
+
// context's data buffer, and the executor io
|
|
2073
|
+
// (leaked after the joins). All three live in
|
|
2074
|
+
// process-lifetime storage
|
|
2075
|
+
// (`process_allocator`), NOT the channel's
|
|
2076
|
+
// caller-owned allocator, so the leak survives
|
|
2077
|
+
// the owner deinitializing its arena or GPA
|
|
2078
|
+
// right after this returns. The handshake above
|
|
2079
|
+
// guarantees the worker touches nothing else —
|
|
2080
|
+
// not this slot (whose caller-owned delivery
|
|
2081
|
+
// buffer the sweep below frees normally), not
|
|
2082
|
+
// the queue, not the channel — so the owner may
|
|
2083
|
+
// free the channel's memory the moment deinit
|
|
2084
|
+
// returns. Bounded (one context and buffer per
|
|
2085
|
+
// abandoned worker, one executor io per
|
|
2086
|
+
// abandoning teardown) and loud (the warning
|
|
2087
|
+
// above).
|
|
2088
|
+
if (slot.worker_thread) |thread| {
|
|
2089
|
+
slot.worker_thread = null;
|
|
2090
|
+
thread.detach();
|
|
2091
|
+
}
|
|
2092
|
+
slot.file_ctx = null;
|
|
2093
|
+
slot.generation = 0;
|
|
2094
|
+
slot.state.store(.idle, .release);
|
|
2095
|
+
self.abandoned_file_workers += 1;
|
|
2096
|
+
abandoned_any = true;
|
|
2097
|
+
}
|
|
2098
|
+
for (&self.slots) |*slot| {
|
|
2099
|
+
if (slot.kind != .spawn or slot.fake) continue;
|
|
2100
|
+
if (slot.state.load(.acquire) != .running) continue;
|
|
2101
|
+
const ctx = slot.spawn_ctx orelse continue;
|
|
2102
|
+
// The same commit/abandon handshake as the file
|
|
2103
|
+
// block above: a worker that committed is in
|
|
2104
|
+
// its epilogue right now and the unconditional
|
|
2105
|
+
// join below collects it; one still blocked is
|
|
2106
|
+
// fenced off the channel forever.
|
|
2107
|
+
ctx.mutex.lock();
|
|
2108
|
+
const committed = ctx.committed;
|
|
2109
|
+
if (!committed) ctx.abandoned = true;
|
|
2110
|
+
ctx.mutex.unlock();
|
|
2111
|
+
if (committed) continue;
|
|
2112
|
+
std.debug.print(
|
|
2113
|
+
"effects teardown: spawned command '{s}' still holds its worker after {d}ms (an escaped descendant is keeping its pipe open past the group kill); abandoning the worker thread and leaking its context so teardown can return safely\n",
|
|
2114
|
+
.{ if (slot.argv_count > 0) slot.argv_slices[0] else "", spawn_deadline_ms },
|
|
2115
|
+
);
|
|
2116
|
+
// DELIBERATE LEAK, same invariant as the file
|
|
2117
|
+
// abandon above: the worker may wake at any
|
|
2118
|
+
// later time (the escaped descendant exits and
|
|
2119
|
+
// EOF finally arrives), so its context — the
|
|
2120
|
+
// argv/stdin copies, the child handshake it
|
|
2121
|
+
// will still lock to reap, its private
|
|
2122
|
+
// framing/collect buffers — and the executor
|
|
2123
|
+
// io stay allocated forever in
|
|
2124
|
+
// `process_allocator` storage. The handshake
|
|
2125
|
+
// guarantees it touches nothing else: not this
|
|
2126
|
+
// slot (whose caller-owned collect buffer the
|
|
2127
|
+
// sweep below frees normally), not the queue
|
|
2128
|
+
// (`produceSpawnLine` re-checks the abandon
|
|
2129
|
+
// under the fence), not the channel. Bounded
|
|
2130
|
+
// and loud, exactly like the file leak.
|
|
2131
|
+
if (slot.worker_thread) |thread| {
|
|
2132
|
+
slot.worker_thread = null;
|
|
2133
|
+
thread.detach();
|
|
2134
|
+
}
|
|
2135
|
+
slot.spawn_ctx = null;
|
|
2136
|
+
slot.generation = 0;
|
|
2137
|
+
slot.state.store(.idle, .release);
|
|
2138
|
+
self.abandoned_spawn_workers += 1;
|
|
2139
|
+
abandoned_any = true;
|
|
2140
|
+
}
|
|
2141
|
+
for (&self.slots) |*slot| joinWorker(slot);
|
|
2142
|
+
if (abandoned_any) {
|
|
2143
|
+
// Leak the executor io too: the abandoned
|
|
2144
|
+
// worker's blocked syscall runs inside it, and
|
|
2145
|
+
// `IoThreaded.deinit` would wait on (or free
|
|
2146
|
+
// under) that thread.
|
|
2147
|
+
self.io_threaded = null;
|
|
1506
2148
|
}
|
|
1507
2149
|
}
|
|
1508
2150
|
if (self.io_threaded) |threaded| {
|
|
1509
2151
|
threaded.deinit();
|
|
1510
|
-
|
|
2152
|
+
process_allocator.destroy(threaded);
|
|
1511
2153
|
self.io_threaded = null;
|
|
1512
2154
|
}
|
|
1513
2155
|
}
|
|
@@ -1545,6 +2187,9 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1545
2187
|
// transport command inert through its existing no-services
|
|
1546
2188
|
// paths instead of dereferencing freed memory.
|
|
1547
2189
|
self.services = null;
|
|
2190
|
+
// Sever the host-call binding for the same reason: its
|
|
2191
|
+
// context belongs to the embedding host.
|
|
2192
|
+
self.host_calls = null;
|
|
1548
2193
|
}
|
|
1549
2194
|
|
|
1550
2195
|
/// Discard every queued completion, freeing heap line payloads
|
|
@@ -1603,6 +2248,13 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1603
2248
|
if (self.window_actions == null) self.window_actions = binding;
|
|
1604
2249
|
}
|
|
1605
2250
|
|
|
2251
|
+
/// Point named host commands at the embedding host's services
|
|
2252
|
+
/// (see `HostCallBinding`). Loop-thread only; the first bind
|
|
2253
|
+
/// sticks.
|
|
2254
|
+
pub fn bindHostCalls(self: *Self, binding: HostCallBinding) void {
|
|
2255
|
+
if (self.host_calls == null) self.host_calls = binding;
|
|
2256
|
+
}
|
|
2257
|
+
|
|
1606
2258
|
/// Switch this channel into session-replay mode: the fake
|
|
1607
2259
|
/// executor (no processes, no network, no file or pasteboard
|
|
1608
2260
|
/// I/O — requests park in their slots) with journaled results as
|
|
@@ -1660,6 +2312,36 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1660
2312
|
self.replay_clock_len += 1;
|
|
1661
2313
|
}
|
|
1662
2314
|
|
|
2315
|
+
/// Journal one launch-env delivery (an `.env` record): the TS
|
|
2316
|
+
/// adapter reports each `envMsgs` value as it dispatches it, so
|
|
2317
|
+
/// replay carries the recorded values instead of re-reading the
|
|
2318
|
+
/// environment. No-op when no session is being recorded.
|
|
2319
|
+
pub fn journalEnvValue(self: *Self, index: u64, msg: []const u8, value: []const u8) void {
|
|
2320
|
+
self.journalNote(.{ .kind = .env, .key = index, .payload = value, .stderr_tail = msg });
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
/// Queue one journaled launch-env delivery for the replay-mode
|
|
2324
|
+
/// envMsgs dispatch (the `.env` record feed). The slices must
|
|
2325
|
+
/// outlive the replay (journal bytes do).
|
|
2326
|
+
pub fn pushReplayEnv(self: *Self, msg: []const u8, value: []const u8) error{EffectNotFound}!void {
|
|
2327
|
+
if (self.replay_env_len >= max_effect_replay_env_entries) return error.EffectNotFound;
|
|
2328
|
+
const index = (self.replay_env_head + self.replay_env_len) % max_effect_replay_env_entries;
|
|
2329
|
+
self.replay_env[index] = .{ .msg = msg, .value = value };
|
|
2330
|
+
self.replay_env_len += 1;
|
|
2331
|
+
}
|
|
2332
|
+
|
|
2333
|
+
/// Pop the next journaled launch-env delivery (FIFO), or null
|
|
2334
|
+
/// when none remain. An empty queue at the first pop means the
|
|
2335
|
+
/// journal carried no `.env` records — the caller re-derives
|
|
2336
|
+
/// from the launch configuration (older recordings).
|
|
2337
|
+
pub fn takeReplayEnv(self: *Self) ?ReplayEnvEntry {
|
|
2338
|
+
if (self.replay_env_len == 0) return null;
|
|
2339
|
+
const entry = self.replay_env[self.replay_env_head];
|
|
2340
|
+
self.replay_env_head = (self.replay_env_head + 1) % max_effect_replay_env_entries;
|
|
2341
|
+
self.replay_env_len -= 1;
|
|
2342
|
+
return entry;
|
|
2343
|
+
}
|
|
2344
|
+
|
|
1663
2345
|
// ------------------------------------------------------------- API
|
|
1664
2346
|
|
|
1665
2347
|
/// Register (or replace) decoded straight-alpha RGBA8 pixels
|
|
@@ -1731,8 +2413,6 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1731
2413
|
// from a cancelled previous occupant may still sit in the
|
|
1732
2414
|
// queue, and the sticky value keeps filtering them after the
|
|
1733
2415
|
// slot is reused (the new generation never matches it).
|
|
1734
|
-
slot.child_id = null;
|
|
1735
|
-
slot.reaping = false;
|
|
1736
2416
|
slot.dropped_pending = 0;
|
|
1737
2417
|
slot.dropped_total = 0;
|
|
1738
2418
|
slot.argv_count = options.argv.len;
|
|
@@ -1758,14 +2438,19 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1758
2438
|
}
|
|
1759
2439
|
slot.line_limit = options.max_line_bytes;
|
|
1760
2440
|
if (options.output == .collect) {
|
|
2441
|
+
// The slot's CHANNEL-owned collect buffer: the drain
|
|
2442
|
+
// hands it to `update` (real mode receives the bytes
|
|
2443
|
+
// from the worker context at commit; fake mode
|
|
2444
|
+
// accumulates into it directly).
|
|
1761
2445
|
slot.collect_buffer = self.allocator.alloc(u8, max_effect_collect_bytes) catch {
|
|
1762
2446
|
return self.reject(options);
|
|
1763
2447
|
};
|
|
1764
|
-
} else if (options.max_line_bytes > max_effect_line_bytes) {
|
|
1765
|
-
slot.line_buffer = self.allocator.alloc(u8, options.max_line_bytes) catch {
|
|
1766
|
-
return self.reject(options);
|
|
1767
|
-
};
|
|
1768
2448
|
}
|
|
2449
|
+
// No slot-side line buffer for spawns: a real worker frames
|
|
2450
|
+
// raised-bound lines into its context's process-lived
|
|
2451
|
+
// buffer (see `SpawnWorkerContext.line_buffer`), and the
|
|
2452
|
+
// fake executor's `feedLine` never frames. (`.stream`
|
|
2453
|
+
// fetches still allocate the slot buffer in `fetch`.)
|
|
1769
2454
|
slot.fake = self.executor == .fake;
|
|
1770
2455
|
slot.state.store(.running, .release);
|
|
1771
2456
|
|
|
@@ -1775,11 +2460,60 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1775
2460
|
self.releaseSpawnSlot(slot);
|
|
1776
2461
|
return self.reject(options);
|
|
1777
2462
|
};
|
|
1778
|
-
|
|
2463
|
+
// The worker's blocking phase touches only this out-of-line
|
|
2464
|
+
// context (argv/stdin copies, the child handshake, its own
|
|
2465
|
+
// framing/collect buffers), never the channel — the seam
|
|
2466
|
+
// that lets teardown abandon a worker whose child's
|
|
2467
|
+
// group-kill did not converge it and still free the channel
|
|
2468
|
+
// (see `SpawnWorkerContext`). Context and buffers come from
|
|
2469
|
+
// `process_allocator`, never `self.allocator`: teardown may
|
|
2470
|
+
// leak them under a live thread, and the channel's
|
|
2471
|
+
// caller-owned allocator dies with the owner. The happy
|
|
2472
|
+
// path frees them in `joinWorker`, through the same
|
|
2473
|
+
// process-lifetime seam.
|
|
2474
|
+
const ctx = process_allocator.create(SpawnWorkerContext) catch {
|
|
1779
2475
|
self.releaseSpawnSlot(slot);
|
|
1780
2476
|
return self.reject(options);
|
|
1781
2477
|
};
|
|
1782
|
-
|
|
2478
|
+
ctx.* = .{
|
|
2479
|
+
.key = options.key,
|
|
2480
|
+
.on_line = options.on_line,
|
|
2481
|
+
.output_mode = options.output,
|
|
2482
|
+
.line_limit = options.max_line_bytes,
|
|
2483
|
+
.exit = .{ .key = options.key, .code = effect_error_exit_code, .reason = .spawn_failed },
|
|
2484
|
+
.argv_count = options.argv.len,
|
|
2485
|
+
.stdin_len = stdin_bytes.len,
|
|
2486
|
+
};
|
|
2487
|
+
// Slices must point into the heap context, so they are
|
|
2488
|
+
// built in place after the copy above.
|
|
2489
|
+
var ctx_offset: usize = 0;
|
|
2490
|
+
for (options.argv, 0..) |arg, index| {
|
|
2491
|
+
@memcpy(ctx.argv_storage[ctx_offset .. ctx_offset + arg.len], arg);
|
|
2492
|
+
ctx.argv_slices[index] = ctx.argv_storage[ctx_offset .. ctx_offset + arg.len];
|
|
2493
|
+
ctx_offset += arg.len;
|
|
2494
|
+
}
|
|
2495
|
+
@memcpy(ctx.stdin_storage[0..stdin_bytes.len], stdin_bytes);
|
|
2496
|
+
if (options.output == .collect) {
|
|
2497
|
+
ctx.collect_buffer = process_allocator.alloc(u8, max_effect_collect_bytes) catch {
|
|
2498
|
+
process_allocator.destroy(ctx);
|
|
2499
|
+
self.releaseSpawnSlot(slot);
|
|
2500
|
+
return self.reject(options);
|
|
2501
|
+
};
|
|
2502
|
+
} else if (options.max_line_bytes > max_effect_line_bytes) {
|
|
2503
|
+
ctx.line_buffer = process_allocator.alloc(u8, options.max_line_bytes) catch {
|
|
2504
|
+
process_allocator.destroy(ctx);
|
|
2505
|
+
self.releaseSpawnSlot(slot);
|
|
2506
|
+
return self.reject(options);
|
|
2507
|
+
};
|
|
2508
|
+
}
|
|
2509
|
+
slot.spawn_ctx = ctx;
|
|
2510
|
+
const thread = std.Thread.spawn(.{}, spawnWorkerMain, .{ self, slot_index, slot.generation, io, ctx }) catch {
|
|
2511
|
+
destroySpawnContext(ctx);
|
|
2512
|
+
slot.spawn_ctx = null;
|
|
2513
|
+
self.releaseSpawnSlot(slot);
|
|
2514
|
+
return self.reject(options);
|
|
2515
|
+
};
|
|
2516
|
+
slot.worker_thread = thread;
|
|
1783
2517
|
}
|
|
1784
2518
|
|
|
1785
2519
|
/// Run an HTTP(S) request on a worker thread and deliver its
|
|
@@ -1850,8 +2584,6 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1850
2584
|
slot.cancel_requested.store(false, .release);
|
|
1851
2585
|
slot.fetch_done.store(false, .release);
|
|
1852
2586
|
// `cancelled_generation` stays sticky, exactly as in `spawn`.
|
|
1853
|
-
slot.child_id = null;
|
|
1854
|
-
slot.reaping = false;
|
|
1855
2587
|
slot.dropped_pending = 0;
|
|
1856
2588
|
slot.dropped_total = 0;
|
|
1857
2589
|
@memcpy(slot.url_storage[0..options.url.len], options.url);
|
|
@@ -1888,7 +2620,7 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1888
2620
|
self.releaseFetchSlot(slot);
|
|
1889
2621
|
return self.rejectFetch(options);
|
|
1890
2622
|
};
|
|
1891
|
-
thread
|
|
2623
|
+
slot.worker_thread = thread;
|
|
1892
2624
|
}
|
|
1893
2625
|
|
|
1894
2626
|
/// Write a whole file on a worker thread — TEA-friendly
|
|
@@ -1929,7 +2661,11 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1929
2661
|
const slot = &self.slots[slot_index];
|
|
1930
2662
|
// A write's buffer holds its payload copy; a read's holds
|
|
1931
2663
|
// the content space plus one spare byte that detects
|
|
1932
|
-
// over-bound files without a stat round trip.
|
|
2664
|
+
// over-bound files without a stat round trip. This is the
|
|
2665
|
+
// slot's CHANNEL-owned buffer (fake-mode storage, real-mode
|
|
2666
|
+
// delivery space the drain hands to `update`); a real
|
|
2667
|
+
// worker's blocking phase gets its own process-lived copy
|
|
2668
|
+
// in `FileWorkerContext.buffer` below.
|
|
1933
2669
|
const buffer_len = if (op == .write) bytes.len else max_effect_file_bytes + 1;
|
|
1934
2670
|
const buffer = self.allocator.alloc(u8, buffer_len) catch {
|
|
1935
2671
|
return self.rejectFile(key, op, on_result);
|
|
@@ -1946,8 +2682,6 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1946
2682
|
slot.on_file = on_result;
|
|
1947
2683
|
slot.cancel_requested.store(false, .release);
|
|
1948
2684
|
// `cancelled_generation` stays sticky, exactly as in `spawn`.
|
|
1949
|
-
slot.child_id = null;
|
|
1950
|
-
slot.reaping = false;
|
|
1951
2685
|
slot.dropped_pending = 0;
|
|
1952
2686
|
slot.dropped_total = 0;
|
|
1953
2687
|
@memcpy(slot.url_storage[0..file_path.len], file_path);
|
|
@@ -1974,11 +2708,42 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
1974
2708
|
self.releaseFetchSlot(slot);
|
|
1975
2709
|
return self.rejectFile(key, op, on_result);
|
|
1976
2710
|
};
|
|
1977
|
-
|
|
2711
|
+
// The worker's blocking phase touches only this out-of-line
|
|
2712
|
+
// context (path copy, op, its own data buffer), never the
|
|
2713
|
+
// channel — the seam that lets teardown abandon a stuck
|
|
2714
|
+
// worker and still free the channel (see
|
|
2715
|
+
// `FileWorkerContext`). Context and buffer both come from
|
|
2716
|
+
// `process_allocator`, never `self.allocator`: teardown may
|
|
2717
|
+
// leak them under a live thread, and the channel's
|
|
2718
|
+
// caller-owned allocator dies with the owner. The happy
|
|
2719
|
+
// path frees both in `joinWorker`, through the same
|
|
2720
|
+
// process-lifetime seam.
|
|
2721
|
+
const ctx = process_allocator.create(FileWorkerContext) catch {
|
|
1978
2722
|
self.releaseFetchSlot(slot);
|
|
1979
2723
|
return self.rejectFile(key, op, on_result);
|
|
1980
2724
|
};
|
|
1981
|
-
|
|
2725
|
+
const worker_buffer = process_allocator.alloc(u8, buffer_len) catch {
|
|
2726
|
+
process_allocator.destroy(ctx);
|
|
2727
|
+
self.releaseFetchSlot(slot);
|
|
2728
|
+
return self.rejectFile(key, op, on_result);
|
|
2729
|
+
};
|
|
2730
|
+
ctx.* = .{
|
|
2731
|
+
.op = op,
|
|
2732
|
+
.buffer = worker_buffer,
|
|
2733
|
+
.payload_len = slot.payload_len,
|
|
2734
|
+
};
|
|
2735
|
+
if (op == .write) @memcpy(worker_buffer[0..bytes.len], bytes);
|
|
2736
|
+
@memcpy(ctx.path_storage[0..file_path.len], file_path);
|
|
2737
|
+
ctx.path_len = file_path.len;
|
|
2738
|
+
slot.file_ctx = ctx;
|
|
2739
|
+
const thread = std.Thread.spawn(.{}, fileWorkerMain, .{ self, slot_index, slot.generation, io, ctx }) catch {
|
|
2740
|
+
process_allocator.free(worker_buffer);
|
|
2741
|
+
process_allocator.destroy(ctx);
|
|
2742
|
+
slot.file_ctx = null;
|
|
2743
|
+
self.releaseFetchSlot(slot);
|
|
2744
|
+
return self.rejectFile(key, op, on_result);
|
|
2745
|
+
};
|
|
2746
|
+
slot.worker_thread = thread;
|
|
1982
2747
|
}
|
|
1983
2748
|
|
|
1984
2749
|
/// Put text on the system clipboard through the platform
|
|
@@ -2042,8 +2807,6 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
2042
2807
|
slot.on_clipboard = on_result;
|
|
2043
2808
|
slot.cancel_requested.store(false, .release);
|
|
2044
2809
|
// `cancelled_generation` stays sticky, exactly as in `spawn`.
|
|
2045
|
-
slot.child_id = null;
|
|
2046
|
-
slot.reaping = false;
|
|
2047
2810
|
slot.dropped_pending = 0;
|
|
2048
2811
|
slot.dropped_total = 0;
|
|
2049
2812
|
slot.url_len = 0;
|
|
@@ -2110,6 +2873,155 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
2110
2873
|
self.wakeHost();
|
|
2111
2874
|
}
|
|
2112
2875
|
|
|
2876
|
+
/// Fire-and-forget named host command: hand `name` + `payload`
|
|
2877
|
+
/// to the bound host services and move on — no key, no result,
|
|
2878
|
+
/// no Msg. This is the delivery path of a transpiled core's
|
|
2879
|
+
/// `host`/`host_bytes` wire records. A channel without bound
|
|
2880
|
+
/// host services drops the send (there is no result route to
|
|
2881
|
+
/// reject into — the honest degrade, documented rather than
|
|
2882
|
+
/// silent-by-accident); session replay never calls the host
|
|
2883
|
+
/// (the send's observable consequences replay through whatever
|
|
2884
|
+
/// results it caused, which ARE journaled).
|
|
2885
|
+
pub fn hostSend(self: *Self, name: []const u8, payload: []const u8) void {
|
|
2886
|
+
if (self.replay) return;
|
|
2887
|
+
if (name.len == 0 or name.len > max_effect_host_name_bytes) return;
|
|
2888
|
+
const binding = self.host_calls orelse return;
|
|
2889
|
+
binding.send_fn(binding.context, name, payload);
|
|
2890
|
+
}
|
|
2891
|
+
|
|
2892
|
+
/// A keyed, routed host command — the generic named host call
|
|
2893
|
+
/// behind a transpiled core's `request` wire records: the host
|
|
2894
|
+
/// performs `name` with `payload` and answers with exactly one
|
|
2895
|
+
/// `feedHostResult(key, ok, bytes)`, delivered as one
|
|
2896
|
+
/// `on_result` Msg (`EffectHostResult`) on the next drain. Key
|
|
2897
|
+
/// discipline differs from spawn/fetch/file/clipboard on
|
|
2898
|
+
/// purpose (the wire contract): issuing a key whose host
|
|
2899
|
+
/// request is still in flight REPLACES it — the old request's
|
|
2900
|
+
/// result is dropped, silently — and `cancelHostRequest` drops
|
|
2901
|
+
/// one without dispatching anything. Rejection is never silent:
|
|
2902
|
+
/// an over-bound name/payload, a key colliding with another
|
|
2903
|
+
/// effect kind, a full slot table, or a real-mode channel with
|
|
2904
|
+
/// no bound host services delivers exactly one err-route Msg
|
|
2905
|
+
/// (`ok = false`, bytes `"rejected"`). Under the fake executor
|
|
2906
|
+
/// the request parks in its slot (inspect with `pendingHostAt`,
|
|
2907
|
+
/// answer with `feedHostResult`).
|
|
2908
|
+
pub fn hostRequest(self: *Self, options: HostRequestOptions) void {
|
|
2909
|
+
self.reclaimSlots();
|
|
2910
|
+
const fake = self.executor == .fake;
|
|
2911
|
+
if (options.name.len == 0 or options.name.len > max_effect_host_name_bytes or
|
|
2912
|
+
options.payload.len > max_effect_host_payload_bytes)
|
|
2913
|
+
{
|
|
2914
|
+
return self.rejectHost(options.key, options.on_result);
|
|
2915
|
+
}
|
|
2916
|
+
if (!fake and self.host_calls == null) return self.rejectHost(options.key, options.on_result);
|
|
2917
|
+
const slot_index = blk: {
|
|
2918
|
+
// In flight = running (no answer yet) OR draining with
|
|
2919
|
+
// an undelivered answer: both are replaced, dropping
|
|
2920
|
+
// the old result silently (its queued entry dies by
|
|
2921
|
+
// generation mismatch at drain). A running occupancy of
|
|
2922
|
+
// another kind is a key collision and rejects; a
|
|
2923
|
+
// draining one is already terminal — its key is free.
|
|
2924
|
+
var replaced: ?usize = null;
|
|
2925
|
+
for (&self.slots, 0..) |*slot, index| {
|
|
2926
|
+
const state = slot.state.load(.acquire);
|
|
2927
|
+
if (state != .running and state != .draining) continue;
|
|
2928
|
+
if (slot.key != options.key) continue;
|
|
2929
|
+
if (slot.kind != .host) {
|
|
2930
|
+
if (state == .running) return self.rejectHost(options.key, options.on_result);
|
|
2931
|
+
continue;
|
|
2932
|
+
}
|
|
2933
|
+
// Tell the host first: a late answer for the old
|
|
2934
|
+
// occupancy must find nothing.
|
|
2935
|
+
if (state == .running and !slot.fake) self.notifyHostCancel(options.key);
|
|
2936
|
+
self.releaseFetchSlot(slot);
|
|
2937
|
+
slot.generation = 0;
|
|
2938
|
+
replaced = index;
|
|
2939
|
+
}
|
|
2940
|
+
break :blk replaced orelse
|
|
2941
|
+
(self.findIdleSlot() orelse return self.rejectHost(options.key, options.on_result));
|
|
2942
|
+
};
|
|
2943
|
+
|
|
2944
|
+
const slot = &self.slots[slot_index];
|
|
2945
|
+
// The buffer holds the payload copy, then the result space.
|
|
2946
|
+
const buffer = self.allocator.alloc(u8, options.payload.len + max_effect_host_result_bytes) catch {
|
|
2947
|
+
return self.rejectHost(options.key, options.on_result);
|
|
2948
|
+
};
|
|
2949
|
+
slot.generation = self.next_generation;
|
|
2950
|
+
self.next_generation +%= 1;
|
|
2951
|
+
if (self.next_generation == 0) self.next_generation = 1;
|
|
2952
|
+
slot.key = options.key;
|
|
2953
|
+
slot.kind = .host;
|
|
2954
|
+
slot.on_line = null;
|
|
2955
|
+
slot.on_exit = null;
|
|
2956
|
+
slot.on_response = null;
|
|
2957
|
+
slot.on_file = null;
|
|
2958
|
+
slot.on_clipboard = null;
|
|
2959
|
+
slot.on_host = options.on_result;
|
|
2960
|
+
slot.cancel_requested.store(false, .release);
|
|
2961
|
+
// `cancelled_generation` stays sticky, exactly as in `spawn`.
|
|
2962
|
+
slot.dropped_pending = 0;
|
|
2963
|
+
slot.dropped_total = 0;
|
|
2964
|
+
@memcpy(slot.url_storage[0..options.name.len], options.name);
|
|
2965
|
+
slot.url_len = options.name.len;
|
|
2966
|
+
if (slot.line_buffer) |old| {
|
|
2967
|
+
self.allocator.free(old);
|
|
2968
|
+
slot.line_buffer = null;
|
|
2969
|
+
}
|
|
2970
|
+
if (slot.fetch_buffer) |old| self.allocator.free(old);
|
|
2971
|
+
slot.fetch_buffer = buffer;
|
|
2972
|
+
@memcpy(buffer[0..options.payload.len], options.payload);
|
|
2973
|
+
slot.payload_len = options.payload.len;
|
|
2974
|
+
slot.body_len = 0;
|
|
2975
|
+
slot.fake = fake;
|
|
2976
|
+
slot.state.store(.running, .release);
|
|
2977
|
+
|
|
2978
|
+
// Fake mode (tests and session replay) parks here: the feed
|
|
2979
|
+
// is the only terminal source.
|
|
2980
|
+
if (fake) return;
|
|
2981
|
+
const binding = self.host_calls.?;
|
|
2982
|
+
binding.request_fn(binding.context, slot.hostName(), options.key, slot.fetchPayload());
|
|
2983
|
+
}
|
|
2984
|
+
|
|
2985
|
+
/// Drop the in-flight host request with `key` without
|
|
2986
|
+
/// dispatching either route — the wire contract's `cancel`
|
|
2987
|
+
/// record. Silent by design (unlike `cancel`, which delivers a
|
|
2988
|
+
/// `.cancelled` terminal): the request's own issuer asked for
|
|
2989
|
+
/// the drop, so there is nothing to report. Also drops a result
|
|
2990
|
+
/// already completed but not yet drained. Unknown keys (and
|
|
2991
|
+
/// keys naming a non-host effect) are a no-op.
|
|
2992
|
+
pub fn cancelHostRequest(self: *Self, key: u64) void {
|
|
2993
|
+
for (&self.slots) |*slot| {
|
|
2994
|
+
const state = slot.state.load(.acquire);
|
|
2995
|
+
if (state != .running and state != .draining) continue;
|
|
2996
|
+
if (slot.kind != .host or slot.key != key) continue;
|
|
2997
|
+
if (state == .running and !slot.fake) self.notifyHostCancel(key);
|
|
2998
|
+
self.releaseFetchSlot(slot);
|
|
2999
|
+
// A queued result entry (fed, undrained) dies by
|
|
3000
|
+
// generation mismatch; zero marks "no occupancy".
|
|
3001
|
+
slot.generation = 0;
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
|
|
3005
|
+
/// Tell the bound host services a request key is dead so the
|
|
3006
|
+
/// host can abort work; best effort, real executor only.
|
|
3007
|
+
fn notifyHostCancel(self: *Self, key: u64) void {
|
|
3008
|
+
const binding = self.host_calls orelse return;
|
|
3009
|
+
const cancel_fn = binding.cancel_fn orelse return;
|
|
3010
|
+
cancel_fn(binding.context, key);
|
|
3011
|
+
}
|
|
3012
|
+
|
|
3013
|
+
fn rejectHost(self: *Self, key: u64, host_fn: ?HostMsgFn) void {
|
|
3014
|
+
self.deliverLoopHost(.{ .key = key, .ok = false, .bytes = "rejected" }, host_fn, true);
|
|
3015
|
+
}
|
|
3016
|
+
|
|
3017
|
+
/// Queue a host terminal produced on the loop thread
|
|
3018
|
+
/// (rejections and feed fallbacks) for the next drain. Bytes
|
|
3019
|
+
/// here are always static.
|
|
3020
|
+
fn deliverLoopHost(self: *Self, result: EffectHostResult, host_fn: ?HostMsgFn, rejected: bool) void {
|
|
3021
|
+
if (host_fn == null) return;
|
|
3022
|
+
self.deliverPending(.{ .host = .{ .result = result, .host_fn = host_fn, .rejected = rejected } });
|
|
3023
|
+
}
|
|
3024
|
+
|
|
2113
3025
|
/// Cancel a running effect by key. After this returns, no
|
|
2114
3026
|
/// further `on_line` Msgs for that spawn are dispatched; one
|
|
2115
3027
|
/// `on_exit` Msg with reason `.cancelled` follows once the
|
|
@@ -2117,6 +3029,8 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
2117
3029
|
/// (worker finished, completions still queued) keeps the same
|
|
2118
3030
|
/// promise: queued lines are discarded and the queued exit is
|
|
2119
3031
|
/// reported as `.cancelled`. Unknown keys are a no-op.
|
|
3032
|
+
/// Host-request slots keep their own contract instead: a cancel
|
|
3033
|
+
/// aimed at one drops it silently (`cancelHostRequest`).
|
|
2120
3034
|
pub fn cancel(self: *Self, key: u64) void {
|
|
2121
3035
|
const slot_index = self.findActiveSlot(key) orelse {
|
|
2122
3036
|
// The worker may have finished with its exit still in
|
|
@@ -2129,6 +3043,7 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
2129
3043
|
return;
|
|
2130
3044
|
};
|
|
2131
3045
|
const slot = &self.slots[slot_index];
|
|
3046
|
+
if (slot.kind == .host) return self.cancelHostRequest(key);
|
|
2132
3047
|
slot.cancelled_generation = slot.generation;
|
|
2133
3048
|
slot.cancel_requested.store(true, .release);
|
|
2134
3049
|
if (slot.fake) {
|
|
@@ -2638,6 +3553,20 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
2638
3553
|
});
|
|
2639
3554
|
return timer_fn(entry.timer);
|
|
2640
3555
|
},
|
|
3556
|
+
.host => |entry| {
|
|
3557
|
+
const host_fn = entry.host_fn orelse continue;
|
|
3558
|
+
self.journalNote(.{
|
|
3559
|
+
.kind = .host,
|
|
3560
|
+
.key = entry.result.key,
|
|
3561
|
+
.payload = entry.result.bytes,
|
|
3562
|
+
// `.host` journal encoding (no new record
|
|
3563
|
+
// fields): the route rides `code`, and
|
|
3564
|
+
// rejections are marked regenerable.
|
|
3565
|
+
.code = @intFromBool(!entry.result.ok),
|
|
3566
|
+
.exit_reason = if (entry.rejected) .rejected else .exited,
|
|
3567
|
+
});
|
|
3568
|
+
return host_fn(entry.result);
|
|
3569
|
+
},
|
|
2641
3570
|
.audio => |entry| {
|
|
2642
3571
|
var event = entry.event;
|
|
2643
3572
|
var audio_fn = entry.audio_fn;
|
|
@@ -2865,6 +3794,41 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
2865
3794
|
});
|
|
2866
3795
|
return clipboard_fn(result);
|
|
2867
3796
|
},
|
|
3797
|
+
.host => {
|
|
3798
|
+
// One terminal per host occupancy, mirroring
|
|
3799
|
+
// `.response`: a mismatched generation means the
|
|
3800
|
+
// occupant was already retired (replaced or
|
|
3801
|
+
// cancelled — its result drops silently, per the
|
|
3802
|
+
// request contract).
|
|
3803
|
+
if (entry.generation != slot.generation) continue;
|
|
3804
|
+
// Take buffer ownership so the slot can be
|
|
3805
|
+
// reused while `update` still reads the bytes.
|
|
3806
|
+
if (self.drain_fetch_body) |old| self.allocator.free(old);
|
|
3807
|
+
self.drain_fetch_body = slot.fetch_buffer;
|
|
3808
|
+
slot.fetch_buffer = null;
|
|
3809
|
+
const payload_len = slot.payload_len;
|
|
3810
|
+
// A cancel that raced the feed (the entry was
|
|
3811
|
+
// already queued) still drops silently.
|
|
3812
|
+
if (cancelled) continue;
|
|
3813
|
+
const host_fn = entry.host_fn orelse continue;
|
|
3814
|
+
const bytes: []const u8 = if (self.drain_fetch_body) |buffer|
|
|
3815
|
+
buffer[payload_len .. payload_len + entry.line_len]
|
|
3816
|
+
else
|
|
3817
|
+
"";
|
|
3818
|
+
const result: EffectHostResult = .{
|
|
3819
|
+
.key = entry.key,
|
|
3820
|
+
.ok = entry.host_ok,
|
|
3821
|
+
.bytes = bytes,
|
|
3822
|
+
};
|
|
3823
|
+
self.journalNote(.{
|
|
3824
|
+
.kind = .host,
|
|
3825
|
+
.key = result.key,
|
|
3826
|
+
.payload = result.bytes,
|
|
3827
|
+
// `.host` journal encoding: route in `code`.
|
|
3828
|
+
.code = @intFromBool(!result.ok),
|
|
3829
|
+
});
|
|
3830
|
+
return host_fn(result);
|
|
3831
|
+
},
|
|
2868
3832
|
}
|
|
2869
3833
|
}
|
|
2870
3834
|
}
|
|
@@ -3241,6 +4205,78 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
3241
4205
|
self.wakeHost();
|
|
3242
4206
|
}
|
|
3243
4207
|
|
|
4208
|
+
/// Number of parked (still-active) fake host requests.
|
|
4209
|
+
pub fn pendingHostCount(self: *Self) usize {
|
|
4210
|
+
var count: usize = 0;
|
|
4211
|
+
for (&self.slots) |*slot| {
|
|
4212
|
+
if (slot.fake and slot.kind == .host and slot.state.load(.acquire) == .running) count += 1;
|
|
4213
|
+
}
|
|
4214
|
+
return count;
|
|
4215
|
+
}
|
|
4216
|
+
|
|
4217
|
+
/// The `index`-th parked fake host request (slot order).
|
|
4218
|
+
pub fn pendingHostAt(self: *Self, index: usize) ?HostRequest {
|
|
4219
|
+
var seen: usize = 0;
|
|
4220
|
+
for (&self.slots) |*slot| {
|
|
4221
|
+
if (!(slot.fake and slot.kind == .host and slot.state.load(.acquire) == .running)) continue;
|
|
4222
|
+
if (seen == index) {
|
|
4223
|
+
return .{
|
|
4224
|
+
.key = slot.key,
|
|
4225
|
+
.name = slot.hostName(),
|
|
4226
|
+
.payload = slot.fetchPayload(),
|
|
4227
|
+
};
|
|
4228
|
+
}
|
|
4229
|
+
seen += 1;
|
|
4230
|
+
}
|
|
4231
|
+
return null;
|
|
4232
|
+
}
|
|
4233
|
+
|
|
4234
|
+
/// The host's (or the test's, or session replay's) answer to
|
|
4235
|
+
/// the in-flight host request with `key`, retiring its slot:
|
|
4236
|
+
/// one terminal Msg through `on_result`, `ok` choosing the
|
|
4237
|
+
/// route and `bytes` riding along. Works for fake-parked AND
|
|
4238
|
+
/// real-bound requests — this is the completion path
|
|
4239
|
+
/// `HostCallBinding.request_fn` answers through. A result over
|
|
4240
|
+
/// `max_effect_host_result_bytes` delivers the err route with a
|
|
4241
|
+
/// teaching message (an opaque payload must never pass for the
|
|
4242
|
+
/// whole one); if the completion queue is somehow full, the
|
|
4243
|
+
/// terminal still lands through the pending ring as an err —
|
|
4244
|
+
/// never a silent ok with lost bytes.
|
|
4245
|
+
pub fn feedHostResult(self: *Self, key: u64, ok: bool, bytes: []const u8) error{EffectNotFound}!void {
|
|
4246
|
+
const slot_index = blk: {
|
|
4247
|
+
const index = self.findActiveSlot(key) orelse return error.EffectNotFound;
|
|
4248
|
+
if (self.slots[index].kind != .host) return error.EffectNotFound;
|
|
4249
|
+
break :blk index;
|
|
4250
|
+
};
|
|
4251
|
+
const slot = &self.slots[slot_index];
|
|
4252
|
+
const buffer = slot.fetch_buffer orelse return error.EffectNotFound;
|
|
4253
|
+
const capacity = buffer.len - slot.payload_len;
|
|
4254
|
+
var delivered_ok = ok;
|
|
4255
|
+
var delivered: []const u8 = bytes;
|
|
4256
|
+
if (bytes.len > capacity) {
|
|
4257
|
+
delivered_ok = false;
|
|
4258
|
+
delivered = "host result over budget";
|
|
4259
|
+
}
|
|
4260
|
+
@memcpy(buffer[slot.payload_len..][0..delivered.len], delivered);
|
|
4261
|
+
slot.body_len = delivered.len;
|
|
4262
|
+
var entry: Entry = .{
|
|
4263
|
+
.kind = .host,
|
|
4264
|
+
.slot_index = @intCast(slot_index),
|
|
4265
|
+
.generation = slot.generation,
|
|
4266
|
+
.key = slot.key,
|
|
4267
|
+
.line_len = @intCast(delivered.len),
|
|
4268
|
+
.host_ok = delivered_ok,
|
|
4269
|
+
.host_fn = slot.on_host,
|
|
4270
|
+
};
|
|
4271
|
+
slot.state.store(.draining, .release);
|
|
4272
|
+
if (!self.enqueue(&entry)) {
|
|
4273
|
+
const host_fn = slot.on_host;
|
|
4274
|
+
self.releaseFetchSlot(slot);
|
|
4275
|
+
self.deliverLoopHost(.{ .key = entry.key, .ok = false }, host_fn, false);
|
|
4276
|
+
}
|
|
4277
|
+
self.wakeHost();
|
|
4278
|
+
}
|
|
4279
|
+
|
|
3244
4280
|
/// Number of recorded (still-armed) fake fx timers.
|
|
3245
4281
|
pub fn pendingTimerCount(self: *Self) usize {
|
|
3246
4282
|
var count: usize = 0;
|
|
@@ -3288,11 +4324,18 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
3288
4324
|
fn ensureIo(self: *Self) !std.Io {
|
|
3289
4325
|
if (io_threaded_supported) {
|
|
3290
4326
|
if (self.io_threaded == null) {
|
|
3291
|
-
|
|
4327
|
+
// The executor and everything it allocates internally
|
|
4328
|
+
// come from `process_allocator`, never the channel's
|
|
4329
|
+
// caller-owned allocator: an abandoning teardown
|
|
4330
|
+
// leaks the executor under a live worker's blocked
|
|
4331
|
+
// syscall, so nothing the worker can reach through
|
|
4332
|
+
// it may die with the owner. The healthy teardown
|
|
4333
|
+
// frees it through the same seam (`deinit`).
|
|
4334
|
+
const threaded = try process_allocator.create(IoThreaded);
|
|
3292
4335
|
// `environ` defaults to `.empty` in `InitOptions`, which
|
|
3293
4336
|
// would hand every spawned child a blank environment (no
|
|
3294
4337
|
// HOME, no PATH) — always pass the host environment.
|
|
3295
|
-
threaded.* = IoThreaded.init(
|
|
4338
|
+
threaded.* = IoThreaded.init(process_allocator, .{
|
|
3296
4339
|
.environ = self.environ orelse fallbackEnviron(),
|
|
3297
4340
|
});
|
|
3298
4341
|
self.io_threaded = threaded;
|
|
@@ -3568,14 +4611,60 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
3568
4611
|
return index;
|
|
3569
4612
|
}
|
|
3570
4613
|
|
|
4614
|
+
/// Join a finished worker's thread and clear its handle.
|
|
4615
|
+
/// Loop-thread only. The reclaim path reaches this only after
|
|
4616
|
+
/// the worker published a non-running slot state — its last
|
|
4617
|
+
/// slot access — so the join blocks for the thread's epilogue
|
|
4618
|
+
/// (a wake nudge and the OS exit), never on child I/O. The
|
|
4619
|
+
/// teardown path (`deinit`) may join a still-running worker;
|
|
4620
|
+
/// convergence there is the kill's and the shutdown flag's
|
|
4621
|
+
/// doing, as documented at that call site.
|
|
4622
|
+
fn joinWorker(slot: *Slot) void {
|
|
4623
|
+
if (io_threaded_supported) {
|
|
4624
|
+
const thread = slot.worker_thread orelse return;
|
|
4625
|
+
slot.worker_thread = null;
|
|
4626
|
+
thread.join();
|
|
4627
|
+
// The join proves the worker is gone: its out-of-line
|
|
4628
|
+
// context (file and spawn workers) has no user left.
|
|
4629
|
+
// Contexts and their buffers are process-lifetime
|
|
4630
|
+
// allocations (see `process_allocator`), so they free
|
|
4631
|
+
// through that seam, not the channel's allocator.
|
|
4632
|
+
if (slot.file_ctx) |ctx| {
|
|
4633
|
+
process_allocator.free(ctx.buffer);
|
|
4634
|
+
process_allocator.destroy(ctx);
|
|
4635
|
+
slot.file_ctx = null;
|
|
4636
|
+
}
|
|
4637
|
+
if (slot.spawn_ctx) |ctx| {
|
|
4638
|
+
destroySpawnContext(ctx);
|
|
4639
|
+
slot.spawn_ctx = null;
|
|
4640
|
+
}
|
|
4641
|
+
}
|
|
4642
|
+
}
|
|
4643
|
+
|
|
4644
|
+
/// Return a spawn worker context and its private buffers to
|
|
4645
|
+
/// `process_allocator` — the happy-path counterpart of the
|
|
4646
|
+
/// abandon leak (spawn-time failures and `joinWorker`).
|
|
4647
|
+
fn destroySpawnContext(ctx: *SpawnWorkerContext) void {
|
|
4648
|
+
if (ctx.line_buffer) |buffer| process_allocator.free(buffer);
|
|
4649
|
+
if (ctx.collect_buffer) |buffer| process_allocator.free(buffer);
|
|
4650
|
+
process_allocator.destroy(ctx);
|
|
4651
|
+
}
|
|
4652
|
+
|
|
3571
4653
|
fn reclaimSlots(self: *Self) void {
|
|
3572
4654
|
for (&self.slots) |*slot| {
|
|
3573
4655
|
switch (slot.state.load(.acquire)) {
|
|
3574
|
-
.done =>
|
|
4656
|
+
.done => {
|
|
4657
|
+
joinWorker(slot);
|
|
4658
|
+
slot.state.store(.idle, .release);
|
|
4659
|
+
},
|
|
3575
4660
|
// A draining slot is reusable once the drain took its
|
|
3576
4661
|
// heap buffer (fetch body or collected stdout — the
|
|
3577
|
-
// terminal Msg was delivered).
|
|
3578
|
-
|
|
4662
|
+
// terminal Msg was delivered). Its worker is already
|
|
4663
|
+
// finished either way: retire the thread now.
|
|
4664
|
+
.draining => {
|
|
4665
|
+
joinWorker(slot);
|
|
4666
|
+
if (slot.fetch_buffer == null and slot.collect_buffer == null) slot.state.store(.idle, .release);
|
|
4667
|
+
},
|
|
3579
4668
|
else => {},
|
|
3580
4669
|
}
|
|
3581
4670
|
}
|
|
@@ -3683,77 +4772,241 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
3683
4772
|
self.wakeHost();
|
|
3684
4773
|
}
|
|
3685
4774
|
|
|
3686
|
-
///
|
|
3687
|
-
///
|
|
3688
|
-
///
|
|
4775
|
+
/// `produceLine` for a real spawn's blocking task: entry
|
|
4776
|
+
/// parameters and drop accounting come from the worker context,
|
|
4777
|
+
/// and every channel touch (the caller-owned allocator for an
|
|
4778
|
+
/// oversized line, the queue, the wake) happens under the
|
|
4779
|
+
/// context's abandon fence — teardown may ABANDON this worker
|
|
4780
|
+
/// at any pre-commit moment, and whoever takes `ctx.mutex`
|
|
4781
|
+
/// first decides: an abandoned task drops the line and walks
|
|
4782
|
+
/// away (the channel may already be freed), while a delivery in
|
|
4783
|
+
/// flight under the lock finishes before teardown can mark the
|
|
4784
|
+
/// abandon. Streaming deliveries therefore keep their live
|
|
4785
|
+
/// arrival order and byte identity on every healthy path.
|
|
4786
|
+
fn produceSpawnLine(self: *Self, ctx: *SpawnWorkerContext, slot_index: u16, generation: u32, bytes: []const u8, truncated: bool) void {
|
|
4787
|
+
var len = @min(bytes.len, ctx.line_limit);
|
|
4788
|
+
var entry: Entry = .{
|
|
4789
|
+
.kind = .line,
|
|
4790
|
+
.slot_index = slot_index,
|
|
4791
|
+
.generation = generation,
|
|
4792
|
+
.key = ctx.key,
|
|
4793
|
+
.truncated = truncated or bytes.len > ctx.line_limit,
|
|
4794
|
+
.dropped_before = ctx.dropped_pending,
|
|
4795
|
+
.line_fn = ctx.on_line,
|
|
4796
|
+
};
|
|
4797
|
+
ctx.mutex.lock();
|
|
4798
|
+
defer ctx.mutex.unlock();
|
|
4799
|
+
if (ctx.abandoned) return;
|
|
4800
|
+
if (len <= max_effect_line_bytes) {
|
|
4801
|
+
@memcpy(entry.line_bytes[0..len], bytes[0..len]);
|
|
4802
|
+
} else if (self.allocator.alloc(u8, len)) |heap| {
|
|
4803
|
+
@memcpy(heap, bytes[0..len]);
|
|
4804
|
+
entry.heap_line = heap;
|
|
4805
|
+
} else |_| {
|
|
4806
|
+
len = max_effect_line_bytes;
|
|
4807
|
+
entry.truncated = true;
|
|
4808
|
+
@memcpy(entry.line_bytes[0..len], bytes[0..len]);
|
|
4809
|
+
}
|
|
4810
|
+
entry.line_len = @intCast(len);
|
|
4811
|
+
if (self.enqueue(&entry)) {
|
|
4812
|
+
ctx.dropped_pending = 0;
|
|
4813
|
+
} else {
|
|
4814
|
+
if (entry.heap_line) |heap| self.allocator.free(heap);
|
|
4815
|
+
ctx.dropped_pending +|= 1;
|
|
4816
|
+
ctx.dropped_total +|= 1;
|
|
4817
|
+
}
|
|
4818
|
+
self.wakeHost();
|
|
4819
|
+
}
|
|
4820
|
+
|
|
4821
|
+
/// Request a kill of a real spawn's child through its worker
|
|
4822
|
+
/// context: record the request (so a kill that races the
|
|
4823
|
+
/// child's publish still lands — the task re-checks after
|
|
4824
|
+
/// publishing) and signal the published id. Loop-thread only
|
|
4825
|
+
/// (cancel, teardown), while the channel is alive; the
|
|
4826
|
+
/// handshake itself lives in the process-lived context so the
|
|
4827
|
+
/// blocking task can take it channel-blind.
|
|
3689
4828
|
fn killPublishedChild(self: *Self, slot: *Slot) void {
|
|
3690
4829
|
_ = self;
|
|
3691
|
-
slot.
|
|
3692
|
-
|
|
3693
|
-
|
|
3694
|
-
|
|
4830
|
+
const ctx = slot.spawn_ctx orelse return;
|
|
4831
|
+
ctx.kill_requested.store(true, .release);
|
|
4832
|
+
killPublishedChildCtx(ctx);
|
|
4833
|
+
}
|
|
4834
|
+
|
|
4835
|
+
/// Send a kill to the published child id, but only while the
|
|
4836
|
+
/// task has not begun reaping (guarded by the context mutex),
|
|
4837
|
+
/// so the pid/handle is guaranteed to still name this process.
|
|
4838
|
+
fn killPublishedChildCtx(ctx: *SpawnWorkerContext) void {
|
|
4839
|
+
ctx.child_mutex.lock();
|
|
4840
|
+
defer ctx.child_mutex.unlock();
|
|
4841
|
+
if (ctx.reaping) return;
|
|
4842
|
+
const id = ctx.child_id orelse return;
|
|
3695
4843
|
if (builtin.os.tag == .windows) {
|
|
4844
|
+
// Windows has no process groups in this sense: the
|
|
4845
|
+
// direct-handle terminate cannot reach descendants, so
|
|
4846
|
+
// an escaped grandchild holding the stdout pipe is
|
|
4847
|
+
// converged by the teardown interruption (the threaded
|
|
4848
|
+
// io cancels the blocked read) or, past the deadline,
|
|
4849
|
+
// by the abandon net. Job objects would kill the whole
|
|
4850
|
+
// tree properly — the future strengthening; not built
|
|
4851
|
+
// here.
|
|
3696
4852
|
_ = std.os.windows.ntdll.NtTerminateProcess(id, @enumFromInt(1));
|
|
3697
4853
|
} else {
|
|
3698
|
-
|
|
4854
|
+
// The child owns its process group (see the spawn in
|
|
4855
|
+
// `runChild`), so the negative-pid form signals every
|
|
4856
|
+
// descendant still in it — the grandchildren of a
|
|
4857
|
+
// shell-wrapped command included, which is what lets
|
|
4858
|
+
// the worker's stdout read reach EOF promptly. The
|
|
4859
|
+
// direct-pid fallback covers a group already gone. A
|
|
4860
|
+
// descendant that LEFT the group (`setsid`, `set -m`)
|
|
4861
|
+
// is out of reach by construction; the teardown
|
|
4862
|
+
// interruption and abandon net bound the worker
|
|
4863
|
+
// instead.
|
|
4864
|
+
std.posix.kill(-id, .KILL) catch {
|
|
4865
|
+
std.posix.kill(id, .KILL) catch {};
|
|
4866
|
+
};
|
|
3699
4867
|
}
|
|
3700
4868
|
}
|
|
3701
4869
|
|
|
3702
4870
|
// ------------------------------------------------------------ worker
|
|
3703
4871
|
|
|
3704
|
-
|
|
4872
|
+
/// Supervises one real spawn, mirroring `fileWorkerMain`: the
|
|
4873
|
+
/// blocking phase (child spawn, stream reads, wait/reap) runs
|
|
4874
|
+
/// as a cancelable `Io` task that touches only its out-of-line
|
|
4875
|
+
/// `SpawnWorkerContext` — plus the queue, under the context's
|
|
4876
|
+
/// abandon fence, for streaming line deliveries (see
|
|
4877
|
+
/// `produceSpawnLine`). Convergence at teardown is normally
|
|
4878
|
+
/// the group-kill's doing (EOF within milliseconds); when a
|
|
4879
|
+
/// descendant escaped the group and keeps the pipe open,
|
|
4880
|
+
/// teardown sets `ctx.interrupt` at half its spawn deadline
|
|
4881
|
+
/// and the supervisor cancels the task (the threaded io
|
|
4882
|
+
/// interrupts the blocked read), and past the full deadline
|
|
4883
|
+
/// the worker is abandoned. After the task ends the supervisor
|
|
4884
|
+
/// COMMITS under the context's mutex — from that point it may
|
|
4885
|
+
/// touch the slot and queue (publishing collect payloads into
|
|
4886
|
+
/// the slot's delivery buffer, posting the exit), and teardown
|
|
4887
|
+
/// will join it — or finds itself abandoned and returns
|
|
4888
|
+
/// without touching the channel again.
|
|
4889
|
+
fn spawnWorkerMain(self: *Self, slot_index: usize, generation: u32, io: std.Io, ctx: *SpawnWorkerContext) void {
|
|
4890
|
+
supervise: {
|
|
4891
|
+
var future = std.Io.concurrent(io, spawnTask, .{ self, ctx, @as(u16, @intCast(slot_index)), generation, io }) catch {
|
|
4892
|
+
// No concurrent capacity: run the blocking phase
|
|
4893
|
+
// inline. Teardown cannot interrupt it, but the
|
|
4894
|
+
// group-kill converges the common case and the
|
|
4895
|
+
// deadline still bounds deinit via the abandon
|
|
4896
|
+
// net. (Deliberately unlike fetch, which REJECTS
|
|
4897
|
+
// when its exchange cannot start cancellably:
|
|
4898
|
+
// fetch joins are unconditional and unbounded,
|
|
4899
|
+
// while a stuck spawn worker — like a file one —
|
|
4900
|
+
// has the abandon safety net.)
|
|
4901
|
+
spawnTask(self, ctx, @intCast(slot_index), generation, io);
|
|
4902
|
+
break :supervise;
|
|
4903
|
+
};
|
|
4904
|
+
superviseWorkerTask(io, &future, &ctx.done, &ctx.interrupt);
|
|
4905
|
+
}
|
|
4906
|
+
ctx.mutex.lock();
|
|
4907
|
+
if (ctx.abandoned) {
|
|
4908
|
+
// Teardown gave up on this worker: the channel may
|
|
4909
|
+
// already be freed. The context (and everything the
|
|
4910
|
+
// task touched through it) is intentionally leaked and
|
|
4911
|
+
// stays valid forever — touch nothing else.
|
|
4912
|
+
ctx.mutex.unlock();
|
|
4913
|
+
return;
|
|
4914
|
+
}
|
|
4915
|
+
ctx.committed = true;
|
|
4916
|
+
ctx.mutex.unlock();
|
|
4917
|
+
// Committed: the channel is alive, and a concurrent
|
|
4918
|
+
// teardown now JOINS this thread instead of abandoning it.
|
|
4919
|
+
// The epilogue below touches the slot and queue freely and
|
|
4920
|
+
// converges within milliseconds (the terminal post gives
|
|
4921
|
+
// up on shutdown).
|
|
3705
4922
|
const slot = &self.slots[slot_index];
|
|
3706
|
-
var exit
|
|
3707
|
-
|
|
3708
|
-
|
|
3709
|
-
|
|
3710
|
-
|
|
3711
|
-
|
|
3712
|
-
|
|
4923
|
+
var exit = ctx.exit;
|
|
4924
|
+
exit.dropped_lines = ctx.dropped_total;
|
|
4925
|
+
slot.dropped_total = ctx.dropped_total;
|
|
4926
|
+
if (ctx.output_mode == .collect) {
|
|
4927
|
+
// Publish the collected payloads into the slot's
|
|
4928
|
+
// channel-owned delivery storage (what the drain hands
|
|
4929
|
+
// to `update`): the blocking phase filled only the
|
|
4930
|
+
// context's process-lived private copies.
|
|
4931
|
+
if (slot.collect_buffer) |delivery| {
|
|
4932
|
+
const publish_len = @min(ctx.collect_len, delivery.len);
|
|
4933
|
+
@memcpy(delivery[0..publish_len], ctx.collect_buffer.?[0..publish_len]);
|
|
4934
|
+
slot.collect_len = publish_len;
|
|
4935
|
+
} else {
|
|
4936
|
+
slot.collect_len = 0;
|
|
4937
|
+
}
|
|
4938
|
+
slot.collect_truncated = ctx.collect_truncated;
|
|
4939
|
+
slot.stderr_ring = ctx.stderr_ring;
|
|
4940
|
+
slot.stderr_total = ctx.stderr_total;
|
|
4941
|
+
}
|
|
3713
4942
|
self.postExit(slot, @intCast(slot_index), generation, io, exit);
|
|
3714
4943
|
// A collect slot still owns its stdout buffer; park it in
|
|
3715
4944
|
// `.draining` until the drain takes the buffer (fetch-style).
|
|
3716
|
-
slot.state.store(if (
|
|
4945
|
+
slot.state.store(if (ctx.output_mode == .collect) .draining else .done, .release);
|
|
3717
4946
|
self.wakeHost();
|
|
3718
4947
|
}
|
|
3719
4948
|
|
|
3720
|
-
|
|
4949
|
+
/// The blocking spawn phase as a cancelable task on the
|
|
4950
|
+
/// executor io. Always records a terminal `ctx.exit` before
|
|
4951
|
+
/// `done`. Touches only the leaked-on-abandon context, the io,
|
|
4952
|
+
/// and — under the context's abandon fence — the completion
|
|
4953
|
+
/// queue for streaming lines (see `SpawnWorkerContext`).
|
|
4954
|
+
fn spawnTask(self: *Self, ctx: *SpawnWorkerContext, slot_index: u16, generation: u32, io: std.Io) void {
|
|
4955
|
+
defer ctx.done.store(true, .release);
|
|
4956
|
+
self.runChild(ctx, slot_index, generation, io);
|
|
4957
|
+
}
|
|
4958
|
+
|
|
4959
|
+
fn runChild(self: *Self, ctx: *SpawnWorkerContext, slot_index: u16, generation: u32, io: std.Io) void {
|
|
3721
4960
|
var child = std.process.spawn(io, .{
|
|
3722
|
-
.argv =
|
|
3723
|
-
.stdin = if (
|
|
4961
|
+
.argv = ctx.argv(),
|
|
4962
|
+
.stdin = if (ctx.stdin_len > 0) .pipe else .ignore,
|
|
3724
4963
|
.stdout = .pipe,
|
|
3725
|
-
.stderr = if (
|
|
4964
|
+
.stderr = if (ctx.output_mode == .collect) .pipe else .ignore,
|
|
4965
|
+
// POSIX: land the child in its OWN process group (id ==
|
|
4966
|
+
// its pid, set before exec) so `killPublishedChild` can
|
|
4967
|
+
// signal the whole descendant tree. Killing only the
|
|
4968
|
+
// direct child leaves a shell-wrapped command's
|
|
4969
|
+
// grandchildren (`sh -c "a; b"` forks `b`) holding the
|
|
4970
|
+
// stdout pipe open — the worker would then block at
|
|
4971
|
+
// read until the orphan exits on its own, stalling
|
|
4972
|
+
// cancel's `.cancelled` terminal and any teardown
|
|
4973
|
+
// joining the worker. Windows has no process groups in
|
|
4974
|
+
// this sense; the direct-handle terminate stands alone
|
|
4975
|
+
// there, as before (see `killPublishedChildCtx` for
|
|
4976
|
+
// the descendant story on both platforms).
|
|
4977
|
+
.pgid = if (builtin.os.tag == .windows) null else 0,
|
|
3726
4978
|
}) catch return;
|
|
3727
4979
|
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
4980
|
+
ctx.child_mutex.lock();
|
|
4981
|
+
ctx.child_id = child.id;
|
|
4982
|
+
ctx.child_mutex.unlock();
|
|
3731
4983
|
// A cancel that raced the spawn still lands.
|
|
3732
|
-
if (
|
|
4984
|
+
if (ctx.kill_requested.load(.acquire)) killPublishedChildCtx(ctx);
|
|
3733
4985
|
|
|
3734
4986
|
// Collect mode drains stderr concurrently so a chatty child
|
|
3735
4987
|
// can never deadlock against a full stderr pipe while we read
|
|
3736
4988
|
// stdout. The reader ends at stderr EOF (the child exiting),
|
|
3737
4989
|
// and the join below runs before the exit is assembled, so
|
|
3738
4990
|
// the tail ring is complete and single-threaded again by the
|
|
3739
|
-
// time it is read.
|
|
4991
|
+
// time it is read. The reader touches only the context (and
|
|
4992
|
+
// the child's pipe), so it is as abandon-safe as the task.
|
|
3740
4993
|
var stderr_thread: ?std.Thread = null;
|
|
3741
4994
|
defer if (stderr_thread) |thread| thread.join();
|
|
3742
4995
|
if (child.stderr) |stderr_file| {
|
|
3743
|
-
stderr_thread = std.Thread.spawn(.{}, stderrTailMain, .{
|
|
4996
|
+
stderr_thread = std.Thread.spawn(.{}, stderrTailMain, .{ ctx, io, stderr_file }) catch null;
|
|
3744
4997
|
}
|
|
3745
4998
|
|
|
3746
4999
|
if (child.stdin) |stdin_file| {
|
|
3747
|
-
stdin_file.writeStreamingAll(io,
|
|
5000
|
+
stdin_file.writeStreamingAll(io, ctx.stdinBytes()) catch {};
|
|
3748
5001
|
stdin_file.close(io);
|
|
3749
5002
|
child.stdin = null;
|
|
3750
5003
|
}
|
|
3751
5004
|
|
|
3752
5005
|
if (child.stdout) |stdout_file| {
|
|
3753
|
-
if (
|
|
3754
|
-
collectStdout(
|
|
5006
|
+
if (ctx.output_mode == .collect) {
|
|
5007
|
+
collectStdout(ctx, io, stdout_file);
|
|
3755
5008
|
} else {
|
|
3756
|
-
self.streamLines(
|
|
5009
|
+
self.streamLines(ctx, slot_index, generation, io, stdout_file);
|
|
3757
5010
|
}
|
|
3758
5011
|
}
|
|
3759
5012
|
|
|
@@ -3761,7 +5014,7 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
3761
5014
|
// stdout closed (before reaping, so a child blocked on a full
|
|
3762
5015
|
// stderr pipe still finishes).
|
|
3763
5016
|
if (stderr_thread == null) {
|
|
3764
|
-
if (child.stderr) |stderr_file| collectStderrTail(
|
|
5017
|
+
if (child.stderr) |stderr_file| collectStderrTail(ctx, io, stderr_file);
|
|
3765
5018
|
}
|
|
3766
5019
|
|
|
3767
5020
|
// Join the stderr reader BEFORE reaping: `child.wait` closes
|
|
@@ -3775,30 +5028,31 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
3775
5028
|
stderr_thread = null;
|
|
3776
5029
|
}
|
|
3777
5030
|
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
|
|
5031
|
+
ctx.child_mutex.lock();
|
|
5032
|
+
ctx.reaping = true;
|
|
5033
|
+
ctx.child_mutex.unlock();
|
|
3781
5034
|
const term = child.wait(io) catch {
|
|
3782
|
-
exit
|
|
5035
|
+
ctx.exit = .{ .key = ctx.key, .code = effect_error_exit_code, .reason = .signaled };
|
|
5036
|
+
if (ctx.kill_requested.load(.acquire)) ctx.exit.reason = .cancelled;
|
|
3783
5037
|
return;
|
|
3784
5038
|
};
|
|
3785
|
-
exit
|
|
3786
|
-
.exited => |code| .{ .key =
|
|
3787
|
-
else => .{ .key =
|
|
5039
|
+
ctx.exit = switch (term) {
|
|
5040
|
+
.exited => |code| .{ .key = ctx.key, .code = code, .reason = .exited },
|
|
5041
|
+
else => .{ .key = ctx.key, .code = effect_error_exit_code, .reason = .signaled },
|
|
3788
5042
|
};
|
|
3789
|
-
if (
|
|
3790
|
-
exit.reason = .cancelled;
|
|
3791
|
-
exit.code = effect_error_exit_code;
|
|
5043
|
+
if (ctx.kill_requested.load(.acquire)) {
|
|
5044
|
+
ctx.exit.reason = .cancelled;
|
|
5045
|
+
ctx.exit.code = effect_error_exit_code;
|
|
3792
5046
|
}
|
|
3793
5047
|
}
|
|
3794
5048
|
|
|
3795
|
-
fn streamLines(self: *Self,
|
|
5049
|
+
fn streamLines(self: *Self, ctx: *SpawnWorkerContext, slot_index: u16, generation: u32, io: std.Io, stdout_file: std.Io.File) void {
|
|
3796
5050
|
var read_buffer: [1024]u8 = undefined;
|
|
3797
5051
|
// Spawns with a raised `max_line_bytes` frame into their
|
|
3798
|
-
//
|
|
5052
|
+
// context's heap buffer; everyone else uses the stack.
|
|
3799
5053
|
var stack_buffer: [max_effect_line_bytes]u8 = undefined;
|
|
3800
|
-
const line_buffer: []u8 =
|
|
3801
|
-
const limit = @min(
|
|
5054
|
+
const line_buffer: []u8 = ctx.line_buffer orelse &stack_buffer;
|
|
5055
|
+
const limit = @min(ctx.line_limit, line_buffer.len);
|
|
3802
5056
|
var line_len: usize = 0;
|
|
3803
5057
|
var truncated = false;
|
|
3804
5058
|
while (true) {
|
|
@@ -3806,7 +5060,7 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
3806
5060
|
const count = stdout_file.readStreaming(io, &read_slices) catch break;
|
|
3807
5061
|
for (read_buffer[0..count]) |byte| {
|
|
3808
5062
|
if (byte == '\n') {
|
|
3809
|
-
self.
|
|
5063
|
+
self.produceSpawnLine(ctx, slot_index, generation, line_buffer[0..line_len], truncated);
|
|
3810
5064
|
line_len = 0;
|
|
3811
5065
|
truncated = false;
|
|
3812
5066
|
} else if (line_len < limit) {
|
|
@@ -3818,35 +5072,58 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
3818
5072
|
}
|
|
3819
5073
|
}
|
|
3820
5074
|
if (line_len > 0 or truncated) {
|
|
3821
|
-
self.
|
|
5075
|
+
self.produceSpawnLine(ctx, slot_index, generation, line_buffer[0..line_len], truncated);
|
|
3822
5076
|
}
|
|
3823
5077
|
}
|
|
3824
5078
|
|
|
3825
|
-
/// Collect-mode stdout: raw bytes into the
|
|
3826
|
-
/// no line framing, bounded by
|
|
3827
|
-
|
|
5079
|
+
/// Collect-mode stdout: raw bytes into the context's private
|
|
5080
|
+
/// buffer, no line framing, bounded by
|
|
5081
|
+
/// `max_effect_collect_bytes`. The committed epilogue publishes
|
|
5082
|
+
/// them into the slot's delivery buffer.
|
|
5083
|
+
fn collectStdout(ctx: *SpawnWorkerContext, io: std.Io, stdout_file: std.Io.File) void {
|
|
3828
5084
|
var read_buffer: [4096]u8 = undefined;
|
|
3829
5085
|
while (true) {
|
|
3830
5086
|
const read_slices: [1][]u8 = .{&read_buffer};
|
|
3831
5087
|
const count = stdout_file.readStreaming(io, &read_slices) catch break;
|
|
3832
5088
|
if (count == 0) break;
|
|
3833
|
-
|
|
5089
|
+
appendCollectedCtx(ctx, read_buffer[0..count]);
|
|
3834
5090
|
}
|
|
3835
5091
|
}
|
|
3836
5092
|
|
|
3837
|
-
fn stderrTailMain(
|
|
3838
|
-
collectStderrTail(
|
|
5093
|
+
fn stderrTailMain(ctx: *SpawnWorkerContext, io: std.Io, stderr_file: std.Io.File) void {
|
|
5094
|
+
collectStderrTail(ctx, io, stderr_file);
|
|
3839
5095
|
}
|
|
3840
5096
|
|
|
3841
5097
|
/// Collect-mode stderr: keep the last
|
|
3842
|
-
/// `max_effect_stderr_tail_bytes` bytes in the
|
|
3843
|
-
|
|
5098
|
+
/// `max_effect_stderr_tail_bytes` bytes in the context's tail
|
|
5099
|
+
/// ring.
|
|
5100
|
+
fn collectStderrTail(ctx: *SpawnWorkerContext, io: std.Io, stderr_file: std.Io.File) void {
|
|
3844
5101
|
var read_buffer: [1024]u8 = undefined;
|
|
3845
5102
|
while (true) {
|
|
3846
5103
|
const read_slices: [1][]u8 = .{&read_buffer};
|
|
3847
5104
|
const count = stderr_file.readStreaming(io, &read_slices) catch break;
|
|
3848
5105
|
if (count == 0) break;
|
|
3849
|
-
|
|
5106
|
+
appendStderrTailCtx(ctx, read_buffer[0..count]);
|
|
5107
|
+
}
|
|
5108
|
+
}
|
|
5109
|
+
|
|
5110
|
+
/// `appendCollected` against the worker context's private
|
|
5111
|
+
/// buffer (single-writer: the blocking task).
|
|
5112
|
+
fn appendCollectedCtx(ctx: *SpawnWorkerContext, bytes: []const u8) void {
|
|
5113
|
+
const buffer = ctx.collect_buffer orelse return;
|
|
5114
|
+
const remaining = buffer.len - ctx.collect_len;
|
|
5115
|
+
const take = @min(bytes.len, remaining);
|
|
5116
|
+
@memcpy(buffer[ctx.collect_len..][0..take], bytes[0..take]);
|
|
5117
|
+
ctx.collect_len += take;
|
|
5118
|
+
if (take < bytes.len) ctx.collect_truncated = true;
|
|
5119
|
+
}
|
|
5120
|
+
|
|
5121
|
+
/// `appendStderrTail` against the worker context's private ring
|
|
5122
|
+
/// (single-writer: the stderr reader).
|
|
5123
|
+
fn appendStderrTailCtx(ctx: *SpawnWorkerContext, bytes: []const u8) void {
|
|
5124
|
+
for (bytes) |byte| {
|
|
5125
|
+
ctx.stderr_ring[ctx.stderr_total % max_effect_stderr_tail_bytes] = byte;
|
|
5126
|
+
ctx.stderr_total += 1;
|
|
3850
5127
|
}
|
|
3851
5128
|
}
|
|
3852
5129
|
|
|
@@ -3854,18 +5131,36 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
3854
5131
|
|
|
3855
5132
|
/// Supervises one fetch: runs the blocking HTTP exchange as a
|
|
3856
5133
|
/// cancelable `Io` task and polls for completion, cancel, and
|
|
3857
|
-
/// the timeout deadline.
|
|
3858
|
-
///
|
|
3859
|
-
///
|
|
5134
|
+
/// the timeout deadline. An exchange that cannot start as a
|
|
5135
|
+
/// cancelable task is REJECTED, never run inline (see
|
|
5136
|
+
/// `startFetchExchange`). Ends by posting exactly one
|
|
5137
|
+
/// `.response` entry and parking the slot in `.draining` (the
|
|
5138
|
+
/// drain retires it after taking the body buffer).
|
|
3860
5139
|
fn fetchWorkerMain(self: *Self, slot_index: usize, generation: u32, io: std.Io) void {
|
|
3861
5140
|
const slot = &self.slots[slot_index];
|
|
3862
5141
|
supervise: {
|
|
3863
|
-
var future =
|
|
3864
|
-
//
|
|
3865
|
-
//
|
|
3866
|
-
//
|
|
3867
|
-
//
|
|
3868
|
-
|
|
5142
|
+
var future = self.startFetchExchange(slot, slot_index, generation, io) catch {
|
|
5143
|
+
// The executor cannot start the exchange as a
|
|
5144
|
+
// cancelable task. Running it inline instead would
|
|
5145
|
+
// observe neither `cancel` nor the timeout — and
|
|
5146
|
+
// teardown joins fetch workers UNCONDITIONALLY on
|
|
5147
|
+
// the guarantee that they poll `shutdown` and
|
|
5148
|
+
// cancel their exchange, so an inline stall would
|
|
5149
|
+
// hang `deinit` forever. REFUSE the exchange: the
|
|
5150
|
+
// honest terminal is `.rejected` (the fetch never
|
|
5151
|
+
// started), journaled at drain like every transport
|
|
5152
|
+
// failure, so replay reproduces the rejection
|
|
5153
|
+
// byte-identically.
|
|
5154
|
+
slot.fetch_status = 0;
|
|
5155
|
+
slot.body_len = 0;
|
|
5156
|
+
slot.fetch_truncated = false;
|
|
5157
|
+
slot.fetch_outcome = .rejected;
|
|
5158
|
+
if (self.fetch_start_rejections.fetchAdd(1, .monotonic) == 0) {
|
|
5159
|
+
std.debug.print(
|
|
5160
|
+
"effects fetch: the executor could not start a cancelable exchange for '{s}'; rejecting the fetch (an inline exchange would evade cancel, the timeout, and teardown)\n",
|
|
5161
|
+
.{slot.fetchUrl()},
|
|
5162
|
+
);
|
|
5163
|
+
}
|
|
3869
5164
|
break :supervise;
|
|
3870
5165
|
};
|
|
3871
5166
|
const poll_ms: u64 = 5;
|
|
@@ -3912,6 +5207,19 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
3912
5207
|
self.wakeHost();
|
|
3913
5208
|
}
|
|
3914
5209
|
|
|
5210
|
+
/// Start the blocking exchange as a cancelable task on the
|
|
5211
|
+
/// executor io — the ONLY way a real exchange may run: an
|
|
5212
|
+
/// exchange the supervisor cannot cancel would break the fetch
|
|
5213
|
+
/// contract (timeout, `cancel`, teardown's unconditional join),
|
|
5214
|
+
/// so a start failure is surfaced to `fetchWorkerMain`, which
|
|
5215
|
+
/// rejects the fetch instead of running it inline. Injectable
|
|
5216
|
+
/// through `fetch_concurrent_start` so tests pin the rejection
|
|
5217
|
+
/// path deterministically.
|
|
5218
|
+
fn startFetchExchange(self: *Self, slot: *Slot, slot_index: usize, generation: u32, io: std.Io) std.Io.ConcurrentError!std.Io.Future(void) {
|
|
5219
|
+
if (!self.fetch_concurrent_start) return error.ConcurrencyUnavailable;
|
|
5220
|
+
return std.Io.concurrent(io, fetchTask, .{ self, slot, @as(u16, @intCast(slot_index)), generation, io });
|
|
5221
|
+
}
|
|
5222
|
+
|
|
3915
5223
|
/// The blocking exchange, run as a cancelable task. Always
|
|
3916
5224
|
/// records a terminal state in the slot before `fetch_done`.
|
|
3917
5225
|
fn fetchTask(self: *Self, slot: *Slot, slot_index: u16, generation: u32, io: std.Io) void {
|
|
@@ -4081,58 +5389,142 @@ pub fn Effects(comptime Msg: type) type {
|
|
|
4081
5389
|
|
|
4082
5390
|
// ------------------------------------------------------- file worker
|
|
4083
5391
|
|
|
4084
|
-
///
|
|
4085
|
-
///
|
|
4086
|
-
///
|
|
5392
|
+
/// Supervises one file effect, mirroring `fetchWorkerMain`: the
|
|
5393
|
+
/// blocking read/write runs as a cancelable `Io` task that
|
|
5394
|
+
/// touches ONLY its out-of-line `FileWorkerContext`, never the
|
|
5395
|
+
/// channel. `cancel` does not interrupt the OS call: it marks
|
|
5396
|
+
/// the generation and the drain rewrites the terminal to
|
|
5397
|
+
/// `.cancelled` (the operation itself may still have completed
|
|
5398
|
+
/// on disk, as `EffectFileOutcome.cancelled` documents).
|
|
5399
|
+
/// Teardown is the one interrupter — past half its file
|
|
5400
|
+
/// deadline it sets `ctx.interrupt` and the supervisor cancels
|
|
5401
|
+
/// the task (the threaded io interrupts the blocked syscall
|
|
5402
|
+
/// where the platform allows it). After the task ends the
|
|
5403
|
+
/// supervisor COMMITS under the context's mutex — from that
|
|
5404
|
+
/// point it may touch the slot and queue, and teardown will
|
|
5405
|
+
/// join it — or finds itself abandoned and returns without
|
|
5406
|
+
/// touching the channel again, walking only the leaked
|
|
5407
|
+
/// context. On the healthy path exactly one `.file` terminal
|
|
4087
5408
|
/// entry posts and the slot parks in `.draining` until the
|
|
4088
|
-
/// drain takes its buffer.
|
|
4089
|
-
|
|
4090
|
-
|
|
4091
|
-
|
|
4092
|
-
|
|
4093
|
-
|
|
5409
|
+
/// drain takes its buffer.
|
|
5410
|
+
fn fileWorkerMain(self: *Self, slot_index: usize, generation: u32, io: std.Io, ctx: *FileWorkerContext) void {
|
|
5411
|
+
supervise: {
|
|
5412
|
+
var future = std.Io.concurrent(io, fileTask, .{ ctx, io }) catch {
|
|
5413
|
+
// No concurrent capacity: run the op inline.
|
|
5414
|
+
// Teardown cannot interrupt it, only outwait or
|
|
5415
|
+
// abandon it — the deadline still bounds deinit.
|
|
5416
|
+
// (Deliberately unlike fetch, which REJECTS when
|
|
5417
|
+
// its exchange cannot start cancellably: fetch
|
|
5418
|
+
// joins are unconditional and unbounded, while a
|
|
5419
|
+
// stuck file worker has the abandon safety net.)
|
|
5420
|
+
fileTask(ctx, io);
|
|
5421
|
+
break :supervise;
|
|
5422
|
+
};
|
|
5423
|
+
superviseWorkerTask(io, &future, &ctx.done, &ctx.interrupt);
|
|
5424
|
+
}
|
|
5425
|
+
ctx.mutex.lock();
|
|
5426
|
+
if (ctx.abandoned) {
|
|
5427
|
+
// Teardown gave up on this worker: the channel may
|
|
5428
|
+
// already be freed. The context (and the buffer the
|
|
5429
|
+
// task just used) is intentionally leaked and stays
|
|
5430
|
+
// valid forever — touch nothing else.
|
|
5431
|
+
ctx.mutex.unlock();
|
|
5432
|
+
return;
|
|
5433
|
+
}
|
|
5434
|
+
ctx.committed = true;
|
|
5435
|
+
ctx.mutex.unlock();
|
|
5436
|
+
// Committed: the channel is alive, and a concurrent
|
|
5437
|
+
// teardown now JOINS this thread instead of abandoning it.
|
|
5438
|
+
// The epilogue below touches the slot and queue freely and
|
|
5439
|
+
// converges within milliseconds (the terminal post gives
|
|
5440
|
+
// up on shutdown).
|
|
4094
5441
|
const slot = &self.slots[slot_index];
|
|
4095
|
-
|
|
4096
|
-
|
|
4097
|
-
|
|
4098
|
-
|
|
5442
|
+
const outcome: EffectFileOutcome = if (ctx.done.load(.acquire)) ctx.outcome else .cancelled;
|
|
5443
|
+
// Publish a read's bytes into the slot's channel-owned
|
|
5444
|
+
// delivery buffer (what the drain hands to `update`): the
|
|
5445
|
+
// blocking phase filled only the context's process-lived
|
|
5446
|
+
// private buffer. Committed means teardown JOINS this
|
|
5447
|
+
// worker, so the slot buffer is safe to touch here.
|
|
5448
|
+
if (ctx.op == .read) {
|
|
5449
|
+
if (slot.fetch_buffer) |delivery| {
|
|
5450
|
+
const publish_len = @min(ctx.read_len, delivery.len);
|
|
5451
|
+
@memcpy(delivery[0..publish_len], ctx.buffer[0..publish_len]);
|
|
5452
|
+
}
|
|
5453
|
+
}
|
|
5454
|
+
slot.body_len = ctx.read_len;
|
|
5455
|
+
self.postFile(slot, @intCast(slot_index), generation, io, outcome, ctx.read_len);
|
|
4099
5456
|
slot.state.store(.draining, .release);
|
|
4100
5457
|
self.wakeHost();
|
|
4101
5458
|
}
|
|
4102
5459
|
|
|
4103
|
-
|
|
5460
|
+
/// Poll a worker's cancelable blocking task to completion:
|
|
5461
|
+
/// converge when the task records `done`, cancel it
|
|
5462
|
+
/// (best-effort syscall interruption through the threaded io)
|
|
5463
|
+
/// when teardown sets `interrupt`, and always await the future
|
|
5464
|
+
/// so the task's frame retires. Shared by the file and spawn
|
|
5465
|
+
/// supervisors; both flags live in the worker's process-lived
|
|
5466
|
+
/// context, so the poll itself is abandon-safe.
|
|
5467
|
+
fn superviseWorkerTask(io: std.Io, future: *std.Io.Future(void), done: *const std.atomic.Value(bool), interrupt: *const std.atomic.Value(bool)) void {
|
|
5468
|
+
const poll_ms: u64 = 5;
|
|
5469
|
+
while (true) {
|
|
5470
|
+
if (done.load(.acquire)) break;
|
|
5471
|
+
if (interrupt.load(.acquire)) {
|
|
5472
|
+
future.cancel(io);
|
|
5473
|
+
break;
|
|
5474
|
+
}
|
|
5475
|
+
std.Io.sleep(io, std.Io.Duration.fromMilliseconds(poll_ms), .awake) catch {};
|
|
5476
|
+
}
|
|
5477
|
+
future.await(io);
|
|
5478
|
+
}
|
|
5479
|
+
|
|
5480
|
+
/// The blocking file op as a cancelable task on the executor
|
|
5481
|
+
/// io. Touches only the leaked-on-abandon context and the io —
|
|
5482
|
+
/// never the slot, the queue, or the channel (see
|
|
5483
|
+
/// `FileWorkerContext`).
|
|
5484
|
+
fn fileTask(ctx: *FileWorkerContext, io: std.Io) void {
|
|
5485
|
+
ctx.outcome = runFileOp(ctx, io);
|
|
5486
|
+
ctx.done.store(true, .release);
|
|
5487
|
+
}
|
|
5488
|
+
|
|
5489
|
+
fn runFileOp(ctx: *FileWorkerContext, io: std.Io) EffectFileOutcome {
|
|
4104
5490
|
const cwd = std.Io.Dir.cwd();
|
|
4105
|
-
const file_path =
|
|
4106
|
-
switch (
|
|
5491
|
+
const file_path = ctx.path();
|
|
5492
|
+
switch (ctx.op) {
|
|
4107
5493
|
.write => {
|
|
4108
5494
|
if (std.fs.path.dirname(file_path)) |parent| {
|
|
4109
|
-
cwd.createDirPath(io, parent) catch return
|
|
5495
|
+
cwd.createDirPath(io, parent) catch |err| return fileOpFailure(err);
|
|
4110
5496
|
}
|
|
4111
5497
|
cwd.writeFile(io, .{
|
|
4112
5498
|
.sub_path = file_path,
|
|
4113
|
-
.data =
|
|
4114
|
-
}) catch return
|
|
5499
|
+
.data = ctx.payload(),
|
|
5500
|
+
}) catch |err| return fileOpFailure(err);
|
|
4115
5501
|
return .ok;
|
|
4116
5502
|
},
|
|
4117
5503
|
.read => {
|
|
4118
5504
|
var file = cwd.openFile(io, file_path, .{}) catch |err| {
|
|
4119
|
-
return if (err == error.FileNotFound) .not_found else
|
|
5505
|
+
return if (err == error.FileNotFound) .not_found else fileOpFailure(err);
|
|
4120
5506
|
};
|
|
4121
5507
|
defer file.close(io);
|
|
4122
5508
|
// The buffer has one byte past the delivery bound:
|
|
4123
5509
|
// filling it proves the file is over-bound.
|
|
4124
|
-
const
|
|
4125
|
-
const len = file.readPositionalAll(io, buffer, 0) catch return .io_failed;
|
|
5510
|
+
const len = file.readPositionalAll(io, ctx.buffer, 0) catch |err| return fileOpFailure(err);
|
|
4126
5511
|
if (len > max_effect_file_bytes) {
|
|
4127
|
-
read_len
|
|
5512
|
+
ctx.read_len = max_effect_file_bytes;
|
|
4128
5513
|
return .truncated;
|
|
4129
5514
|
}
|
|
4130
|
-
read_len
|
|
5515
|
+
ctx.read_len = len;
|
|
4131
5516
|
return .ok;
|
|
4132
5517
|
},
|
|
4133
5518
|
}
|
|
4134
5519
|
}
|
|
4135
5520
|
|
|
5521
|
+
/// An interrupted blocking op reports `.cancelled` (only
|
|
5522
|
+
/// teardown cancels the task); every other failure stays the
|
|
5523
|
+
/// blanket `.io_failed`.
|
|
5524
|
+
fn fileOpFailure(err: anyerror) EffectFileOutcome {
|
|
5525
|
+
return if (err == error.Canceled) .cancelled else .io_failed;
|
|
5526
|
+
}
|
|
5527
|
+
|
|
4136
5528
|
/// The terminal file result must never be dropped: retry until
|
|
4137
5529
|
/// the loop thread drains space, giving up only on shutdown.
|
|
4138
5530
|
fn postFile(self: *Self, slot: *Slot, slot_index: u16, generation: u32, io: std.Io, outcome: EffectFileOutcome, read_len: usize) void {
|