12-system-resources/09-external-commands.protos

Repository
guillermomolina/protos
Commit
379c6fa63685c39a5954cfbd577bfda3b4df8e75
Tree
8cd4f4afe29ae4c3866381f38c1858108e9799f6
Blob
caae38d0285f46a158deb46e08d3277211bb7449
Source
View exact source on GitHub
// THE LICENSED WORK IS PROVIDED UNDER THE TERMS OF THE ADAPTIVE PUBLIC LICENSE
// ("LICENSE") AS FIRST COMPLETED BY: Guillermo Adrián Molina. ANY USE, PUBLIC
// DISPLAY, PUBLIC PERFORMANCE, REPRODUCTION OR DISTRIBUTION OF, OR PREPARATION OF
// DERIVATIVE WORKS BASED ON, THE LICENSED WORK CONSTITUTES RECIPIENT'S ACCEPTANCE
// OF THIS LICENSE AND ITS TERMS, WHETHER OR NOT SUCH RECIPIENT READS THE TERMS OF
// THE LICENSE. "LICENSED WORK" AND "RECIPIENT" ARE DEFINED IN THE LICENSE. A COPY
// OF THE LICENSE IS LOCATED IN THE TEXT FILE ENTITLED "LICENSE.TXT" ACCOMPANYING
// THE CONTENTS OF THIS FILE. IF A COPY OF THE LICENSE DOES NOT ACCOMPANY THIS
// FILE, A COPY OF THE LICENSE MAY ALSO BE OBTAINED AT THE FOLLOWING WEB SITE:
// https://github.com/guillermomolina/protos
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
// the specific language governing rights and limitations under the License.

// Lesson: external commands and byte pipelines with std:io/commands.
//
// Run from the product root with the explicit execution grant:
//   bin/protos --allow-execution protos/tutorials/12-system-resources/09-external-commands.protos
// It uses the host programs /bin/echo, /bin/cat, /bin/ls and /bin/sleep. Without the grant
// there is no `execution` binding and nothing here can start a program; importing the
// module never grants authority. Every line is reported through an explicit Process
// writer, so the authority-free tutorial sweep does not run this lesson.

Commands: import("std:io/commands")
ProcessStreams: import("std:io/process_streams")
out: ProcessStreams.stdoutWriter(process)

say: (text) => { out.writeLine(text).value() }
yes: (condition) => { if(condition) { "yes" } else { "no" } }

// A borrowed byte sink that keeps what it receives, so the lesson can inspect it.
// Text is decoded here, at the application's own boundary, never by the pipeline.
sink: () => {
    state: { received: Encoding.UTF8.encode(""); closes: 0 }
    endpoint: null
    endpoint = {
        write: (value) => {
            for(octet in value) { state.received.add(octet) }
            (() => { endpoint }).future()
        }
        close: () => {
            state.closes = state.closes + 1
            (() => { null }).future()
        }
    }
    { endpoint: endpoint; state: state }
}

// 1. Descriptions are frozen data. The Array and Map are copied: changing them later
//    does not change the description, and the description carries no authority.
arguments: ["one description,", "many runs"]
echo: Commands.command("/bin/echo", arguments, Map(), null)
arguments[0] = "changed later"
say("description argument kept: " + echo.arguments[0])
say("description is data only: " + yes(echo.slotNames().size() == 4))

// 2. One command. The grant is passed explicitly; stdout goes to a borrowed sink.
first: sink()
single: Commands.run(execution, [echo], null, first.endpoint, [null]).wait().value()
say("single output: " + Encoding.UTF8.decode(first.state.received))

// 3. A pipeline: stage 0 stdout feeds stage 1 stdin. Bytes are forwarded unchanged.
cat: Commands.command("/bin/cat", [], Map(), null)
second: sink()
piped: Commands.run(execution, [echo, cat, cat], null, second.endpoint, [null, null, null]).wait().value()
say("pipeline output: " + Encoding.UTF8.decode(second.state.received))

// 4. The result is frozen data. /bin/ls reports a missing path on stderr and exits with
//    a nonzero code: that is a status, not a failure.
missing: Commands.command("/bin/ls", ["/nonexistent-protos-tutorial"], Map(), null)
errors: sink()
result: Commands.run(execution, [missing], null, null, [errors.endpoint]).wait().value()
say("success: " + yes(result.success))
say("exited with a nonzero code: " + yes(result.statuses[0].exited() && (result.statuses[0].exitCode() != 0)))
say("no failure recorded for it: " + yes(result.failures.size() == 0))
say("stderr kept separate: " + yes(errors.state.received.size() > 0))

// 5. wait() answers a fresh Future each time; every observation sees the same result.
//    stop() never waits: it requests termination and closes the child's endpoints.
//    The run reads its input only after the child was started, so stopping from that
//    first read stops a live, acquired child (not a run that has not launched yet).
blocker: execution.start("/bin/sleep", ["30"], Map(), null).value()
sleeper: null
input: {
    read: (maxBytes) => {
        // The stop runs as a separate Task, after the run registered this pending read,
        // so the stop cancels it. blocker.wait() is a genuine pending operation Future.
        (() => {
            sleeper.stop()
            null
        }).future()
        blocker.wait()
    }
}
sleeper = Commands.run(execution, [Commands.command("/bin/sleep", ["30"], Map(), null)], input, null, [null])
firstObservation: sleeper.wait()
secondObservation: sleeper.wait()
say("fresh observations: " + yes(firstObservation !== secondObservation))
stopped: firstObservation.value()
say("same result: " + yes(secondObservation.value() === stopped))
say("stopped after the child started: " + yes(stopped.stopped && stopped.started[0]))
blocker.terminate().value()
blocker.wait().value()

// 6. Endpoints you pass are borrowed: the run never closes them.
say("borrowed sinks still open: " + yes((first.state.closes == 0) && (second.state.closes == 0) &&
    (errors.state.closes == 0)))