## Copies that cross the intent -> world boundary (ANALYSIS 4.1, DESIGN 4.3). ## ## Mummy runs the websocket handlers on several worker threads. The world is read and written under ## the one global lock, but the intents are parsed outside it. Nim's ORC reference counts are not ## atomic, so any `JsonNode` or `string` payload that is reachable from both an intent tree and the ## world can be ref-counted by two threads at once: once under the lock (an egress walk) and once ## outside it (the intent's `env` dying at the end of `dispatch`). That is a lost update, i.e. a ## premature free or a leak. ## ## Rule: an intent value is copied *at the boundary* into memory nothing else aliases. `copy()` is ## not enough for a `JsonNode`, because std/json rebuilds the nodes but a `JString`'s `str` field is ## still a string assignment and thus shares the intent's payload. Serialise + parse allocates a ## complete second tree, string payloads included. `detachedString` does the same for a bare string. import std/json import props proc detachedString*(s: string): string = ## A string whose payload the caller does not share. Empty strings have no payload to share. if s.len == 0: return "" result = newString(s.len) copyMem(addr result[0], unsafeAddr s[0], s.len) proc detachedJson*(node: JsonNode): JsonNode = ## A deep copy of `node` that shares no node and no string payload with it. Serialise/parse is the ## portable way to get that guarantee from std/json; props and flags are small and bounded. if node.isNil: nil else: parseJson($node) proc detachedProps*(p: Props): Props = ## The three property buckets, each detached. Keys and values both come from the intent on ## `token.create`/`character.create`, so a shallow bucket copy would still alias them. for b in PropBucket: result[b] = detachedJson(p[b])