S2 take once in a bundle too, Go and TypeScript

A bundle holder takes an ask once through the runtime's create with the
ask's bound as the key's time to live: stdio.KeptState.TakeOnce and
TypeScript takeOnce; stdio.TakenState and TakenKey are the one name, which
process refers to.

Builds: design 47 H2 §775, §820; H-A-359
This commit is contained in:
2026-11-21 23:12:58 +01:00
parent 423de0e8a2
commit 25b3030a93
5 changed files with 125 additions and 14 deletions
+10 -14
View File
@@ -399,23 +399,19 @@ func (s State) delete(key string) error {
return nil
}
// TakenState is the state a holder of a kept call keeps the ids of the asks it took in (design 47 H2 §775, §820): a
// state of 8 MiB whose keys live the ask's bound and are deleted by their time to live alone, never pruned.
const TakenState = "taken"
// TakenState is the state a holder of a kept call keeps the ids of the asks it took in: stdio.TakenState.
const TakenState = stdio.TakenState
// TakenKey is the key an ask taken from seat is kept under in TakenState: `<seat>.<ask>`.
func TakenKey(seat, ask string) string { return seat + "." + ask }
// TakenKey is the key an ask taken from seat is kept under in TakenState: stdio.TakenKey.
func TakenKey(seat, ask string) string { return stdio.TakenKey(seat, ask) }
// TakeOnce says whether this holder takes the ask ask of seat now (design 47 H2 §775; ADR 0668 §2): the first time it
// is given, it is kept under TakenKey for the ask's bound and TakeOnce answers true; given again within the bound,
// false, and the holder acts once. s is the holder's TakenState, declared `key-ttl`. An ask with no id, or an id that is
// not one key, is refused: a kept call carries its id.
// TakeOnce says whether this holder takes the ask ask of seat now (design 47 H2 §775; ADR 0668 §2), as
// stdio.KeptState.TakeOnce does for a bundle: the first time it is given, it is kept under TakenKey for the ask's bound
// and TakeOnce answers true; given again within the bound, false, and the holder acts once. s is the holder's
// TakenState, declared `key-ttl`. An ask with no id, or an id that is not one key, is refused: a kept call carries its id.
func (s State) TakeOnce(seat, ask string, bound time.Duration) (bool, error) {
if err := checkAskID(ask); err != nil {
return false, fmt.Errorf("taking an ask of %s: %w", seat, err)
}
if seat == "" || strings.ContainsAny(seat, ".*> ") {
return false, fmt.Errorf("taking the ask %s: %q is not a seat's name", ask, seat)
if p := stdio.TakenProblem(seat, ask); p != "" {
return false, fmt.Errorf("taking an ask of %s: %s", seat, p)
}
_, err := s.CreateTTL(TakenKey(seat, ask), map[string]string{"seat": seat, "ask": ask}, max(bound, MinTTL))
if errors.Is(err, stdio.ErrChanged) {
+34
View File
@@ -2,6 +2,8 @@ package stdio
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
)
@@ -201,6 +203,38 @@ func (s KeptState) CreateTTL(key string, value any, ttl time.Duration) (uint64,
return s.revisionOf(s.ask("create", map[string]any{"key": key, "value": value, "ttl_seconds": ttlSeconds(ttl)}))
}
// TakenState is the state a holder of a kept call keeps the ids of the asks it took in (design 47 H2 §775, §820): a
// state of 8 MiB whose keys live the ask's bound and are deleted by their time to live alone, never pruned.
const TakenState = "taken"
// TakenKey is the key an ask taken from seat is kept under in TakenState: `<seat>.<ask>`.
func TakenKey(seat, ask string) string { return seat + "." + ask }
// TakenProblem is why seat and ask name no taken key, or empty: a seat's name and an ask's id are each one key token.
func TakenProblem(seat, ask string) string {
switch {
case ask == "" || strings.ContainsAny(ask, ".*> "):
return fmt.Sprintf("%q is not an ask id: an ask id holds no dot and no wildcard, naming one key and no other", ask)
case seat == "" || strings.ContainsAny(seat, ".*> "):
return fmt.Sprintf("%q is not a seat's name", seat)
}
return ""
}
// TakeOnce says whether this holder takes the ask ask of seat now (design 47 H2 §775; ADR 0668 §2; H-A-359): the
// first time it is given it is kept under TakenKey for the ask's bound and TakeOnce answers true; given again within
// the bound, false, and the holder acts once. s is the holder's TakenState, declared `key-ttl`.
func (s KeptState) TakeOnce(seat, ask string, bound time.Duration) (bool, error) {
if p := TakenProblem(seat, ask); p != "" {
return false, fmt.Errorf("taking an ask of %s: %s", seat, p)
}
_, err := s.CreateTTL(TakenKey(seat, ask), map[string]string{"seat": seat, "ask": ask}, max(bound, time.Second))
if errors.Is(err, ErrChanged) {
return false, nil
}
return err == nil, err
}
// Update writes a key only when it is still at revision, and returns the new one; a key changed
// meanwhile is refused, so of two writers that read one value only the first writes.
func (s KeptState) Update(key string, value any, revision uint64) (uint64, error) {
+28
View File
@@ -56,6 +56,9 @@ func TestABundleKeepsAndWatchesStateThroughTheRuntime(t *testing.T) {
}
return State("servers").PutTTL(a["key"].(string), 1, 90*time.Second)
}},
{Name: "take", Run: func(a map[string]any) (any, error) {
return State("servers").TakeOnce(a["seat"].(string), a["ask"].(string), 10*time.Minute)
}},
}, inR, outW)
}()
lines := bufio.NewScanner(outR)
@@ -219,6 +222,31 @@ func TestABundleKeepsAndWatchesStateThroughTheRuntime(t *testing.T) {
t.Fatalf("the put answered %v", r)
}
}
// Design 47 H2 §775, H-A-359: a bundle takes an ask once: the create of <seat>.<ask> with the ask's bound as its time
// to live answers true, the runtime's refusal as changed answers false, and an ask with no id is refused unasked.
for i, exists := range []bool{false, true} {
send(map[string]any{"jsonrpc": "2.0", "id": 40 + i, "method": "tools/call", "params": map[string]any{"name": "take",
"arguments": map[string]any{"seat": "git", "ask": "a-7"}}})
asked := next()
p := asked["params"].(map[string]any)
if asked["method"] != "mesh/state.create" || p["key"] != "git.a-7" || p["ttl_seconds"] != float64(600) {
t.Fatalf("asked %v", asked)
}
if exists {
send(map[string]any{"jsonrpc": "2.0", "id": asked["id"], "error": map[string]any{"code": CodeChanged, "message": "exists"}})
} else {
send(map[string]any{"jsonrpc": "2.0", "id": asked["id"], "result": map[string]any{"revision": 5}})
}
r := next()
if text := fmt.Sprint(r["result"]); r["id"] != float64(40+i) || !strings.Contains(text, map[bool]string{false: "true", true: "false"}[exists]) {
t.Fatalf("a take, the key existing %v, answered %v", exists, r)
}
}
send(map[string]any{"jsonrpc": "2.0", "id": 42, "method": "tools/call", "params": map[string]any{"name": "take",
"arguments": map[string]any{"seat": "git", "ask": ""}}})
if r := next(); r["id"] != float64(42) || !strings.Contains(fmt.Sprint(r), "is not an ask id") {
t.Fatalf("a take with no ask id answered %v", r)
}
if !errors.Is(&refused{code: CodeChanged, message: "x"}, ErrChanged) {
t.Fatal("a refusal coded -32010 is not ErrChanged")
}
+35
View File
@@ -133,6 +133,41 @@ function withinOneCall(key: string, value: unknown): void {
}
}
/** The state a holder of a kept call keeps the ids of the asks it took in (design 47 H2 §775, §820): Go's `stdio.TakenState`. */
export const TAKEN_STATE = "taken";
/** The key an ask taken from `seat` is kept under in TAKEN_STATE: `<seat>.<ask>`. */
export function takenKey(seat: string, ask: string): string {
return `${seat}.${ask}`;
}
/** The code of the runtime's refusal of a create whose key has a value (Go's `stdio.CodeChanged`). */
const CODE_CHANGED = -32010;
/**
* Whether this holder takes the ask `ask` of `seat` now (design 47 H2 §775; H-A-359), as Go's `KeptState.TakeOnce`: the
* first time it is given it is created under takenKey with the ask's bound as its time to live (the runtime's
* `mesh/state.create`) and this resolves true; given again within the bound, false, and the holder acts once.
* `stateName` is the holder's TAKEN_STATE, declared `key-ttl`.
*/
export async function takeOnce(seat: string, ask: string, boundMs: number, stateName = TAKEN_STATE): Promise<boolean> {
if (!ask || /[.*> ]/.test(ask)) throw new Error(`taking an ask of ${seat}: ${JSON.stringify(ask)} is not an ask id: an ask id holds no dot and no wildcard, naming one key and no other`);
if (!seat || /[.*> ]/.test(seat)) throw new Error(`taking the ask ${ask}: ${JSON.stringify(seat)} is not a seat's name`);
refusedUnannounced(stateName);
try {
await boundChannel().ask("mesh/state.create", {
state: stateName,
key: takenKey(seat, ask),
value: { seat, ask },
ttl_seconds: Math.max(1, Math.floor(boundMs / 1000)),
});
return true;
} catch (e) {
if ((e as { code?: number }).code === CODE_CHANGED) return false;
throw e;
}
}
/** A state this module keeps (by its local name) or reads (`<module>.<name>`). */
export function state<T = unknown>(name: string): State<T> {
const bound = (): StateChannel => {
+18
View File
@@ -1034,4 +1034,22 @@ async function newTest5(): Promise<void> {
async function newTest6(): Promise<void> {
const { state, CHUNK_BYTES } = await import("../dist/state/index.js");
await assert.rejects(state("s").put("k", { text: "x".repeat(CHUNK_BYTES) }), /512 KiB/);
// design 47 H2 §775, H-A-359: a holder given the same ask id twice acts once
const { takeOnce, useStateChannel } = await import("../dist/state/index.js");
const created = new Set<string>();
const asked: unknown[] = [];
useStateChannel({
ask: async (method: string, params: unknown) => {
asked.push([method, params]);
const p = params as { key: string };
if (created.has(p.key)) throw Object.assign(new Error("exists"), { code: -32010 });
created.add(p.key);
return { revision: 1 };
},
watch: async () => {},
} as never);
assert.equal(await takeOnce("git", "a-7", 600_000), true);
assert.equal(await takeOnce("git", "a-7", 600_000), false);
assert.deepEqual(asked[0], ["mesh/state.create", { state: "taken", key: "git.a-7", value: { seat: "git", ask: "a-7" }, ttl_seconds: 600 }]);
await assert.rejects(takeOnce("git", "", 1000), /is not an ask id/);
}