But note: We want to avoid sending the entire tree on every update. That's where diffing comes in.
Diffing:
The client maintains a current UI tree (or a virtual tree) and the server sends a new state (or a diff) to update the UI.
We have two common approaches:
a. The server sends the entire new tree and the client does a diff (like React's reconciliation). This is simple but can be inefficient for large trees.
b. The server sends a minimal set of changes (like a JSON Patch) that the client applies.
However, note that in server-driven UI, the server might not have the full tree on the client? Actually, the client does have the current tree because it rendered it.
We can consider:
The client sends the current UI state (maybe a version or a hash) and the server responds with the changes needed to get to the new state.
But note: the server might not know the exact client state because of network issues or client modifications? Actually, in a typical server-driven UI, the server is the source of truth and the client is just a renderer. So the server can compute the new state from the current state (which it knows) and the user's actions.
So, let's assume the server has the current state (or can compute it) and sends the next state. However, we don't want to send the entire tree every time.
We can do:
The server and client agree on a way to identify nodes (like keys). Then the server can send a diff in terms of:
Insertions: new nodes with keys and their description.
Deletions: keys of nodes to remove.
Updates: keys of nodes with new properties.
But note: moving a node (changing its parent) would be a deletion and insertion? Or we can have moves.
Alternatively, we can use a tree diffing algorithm. However, that requires the server to compute the diff, which might be heavy. Or the client does the diff, but then the server must send the entire new tree.
Given that the server is already computing the new state (from state change), it might be easier for the server to compute the minimal set of changes? But if the state change is complex, computing the minimal diff might be as heavy as sending the entire tree.
Another idea: use a virtual tree representation and send the new virtual tree, and let the client diff. But then we are sending the entire tree again.
We need to balance between:
- Bandwidth: sending minimal data.
- Server load: computing diffs.
- Client load: computing diffs.
Considering that the server is already doing the business logic and state management, and the client is just a renderer, it might be acceptable for the server to compute the diff? But note that the server might be stateless and not have the current UI tree? Actually, if we are doing server-driven UI, the server typically holds the state and the UI is a function of state. So the server can compute the entire UI tree for the new state, but then it can also compute the diff if it has the old UI tree? But the old UI tree is on the client.
So, without the old UI tree, the server cannot compute the diff? Unless the server also keeps the last sent UI tree? That would break statelessness.
Alternatively, we can have the client send the current state (or a hash of the current UI tree) and the server computes the new state and the diff? But then the server must store the current UI tree for the client? That's stateful.
Let's consider a different approach:
The server sends a new state (the entire UI tree) and the client does the diff. This is simple and stateless on the server. The client has the old tree and the new tree and can do a diff (like React). The downside is bandwidth.
We can compress the UI tree? But still, for large trees, it's heavy.
Alternatively, we can have a hybrid:
- The server sends a list of changes (like a patch) for the state change. But then the server must know what the current UI tree is? Actually, the server knows the state change (from user action) and can compute what nodes are added, removed, updated? But without the tree structure, it's hard to know if a node was moved.
Given the complexity, maybe we start with the entire tree and then optimize later? But we are designing a protocol, so we should consider efficiency.
Another idea: use a component-based approach with keys and let the server send only the changed components? But then the client must be able to map the keys to the tree.
We can have:
- Each component in the tree has a unique key (assigned by the server, stable across renders).
- The server sends a list of components (with their keys) that are in the new tree, and also a list of keys that are removed? But then the client must reconstruct the tree? Actually, the server can send the entire tree but with keys, and then the client can do a keyed diff (like React's keyed reconciliation). This is efficient because the client can match by key and only update changed ones.
So, let's decide:
The server sends a tree of components, each with:
- type (string, identifies the component)
- key (string, unique among siblings, and stable across renders for the same logical component)
- props (object)
- children (array)
The client maintains a tree of rendered components (with keys) and when a new tree comes, it does:
code
For each node in the new tree (with key):
If there's a node with the same key in the old tree (at the same level? Actually, in keyed diff, we don't require same level, but we typically do by parent) then update that node.
Otherwise, create a new node.
For each node in the old tree (with key) that is not in the new tree, remove it.
But note: the tree structure matters. We are matching by key and parent? Actually, in React, keys are unique among siblings, so we match by parent and key.
So, the client must have the old tree and the new tree, and do a diff by:
code
- Group children of each parent by key.
- Then, for each parent, compare the keys of old and new children.
This is efficient because we don't have to traverse the entire tree for every node, just the children of each parent.
However, note that moving a node from one parent to another would be a removal from the old parent and an addition to the new parent.
So, the protocol:
code
Safety:
We must protect against malicious or erroneous server responses.
The server should not be able to execute arbitrary code on the client. So we cannot have the server send code (like JavaScript) to be executed.
The client should only have a set of known components (with known behavior) and the server can only configure these components with data.
So, the protocol should be data-only, and the client must validate:
code
- The type of each node must be one of the known component types.
- The props for each component type must match the expected schema (type, required, etc.)
Also, we must consider:
code
- Infinite recursion: the server could send a tree that is too deep or too large, causing the client to crash. We must set limits on tree depth and total nodes.
- Circular references: the server could send a tree with a cycle? But in a tree, by definition, there are no cycles. However, if we allow the server to send a graph? We are sending a tree, so no cycles. But we must validate that the structure is a tree (no shared nodes, no cycles). However, if we are sending a tree as a nested structure, it's naturally a tree. But if we use references (by key) to other nodes? We are not doing that. We are sending a nested structure.
- Memory: the server could send a very large tree. We must have a maximum size (number of nodes) and maximum depth.
- Type confusion: the server might send a component type that the client doesn't know. We must ignore or error on unknown types.
- Prop validation: each component type has a set of expected props. We must validate that the props are of the correct type and that required props are present.
- Also, we must validate that the keys are strings and unique among siblings? Actually, the client must check for duplicate keys in the same parent's children? The server should not send duplicate keys, but the client must handle it gracefully (maybe by generating a unique key for the duplicate? or error?).
Proposed Protocol:
code
4. Additional considerations:
code
- How does the server know the current state? In a typical server-driven UI, the server holds the state and the client sends user events (like button clicks) to the server, and the server computes the new state and sends a new UI tree.
- We might want to send only the changed part of the tree? But note: the server doesn't know which part of the tree the client has? Actually, the client has the entire tree. So the server can compute the entire new tree and send it. Then the client diffs.
- However, if the tree is very large, we might want to send only the changed subtree? But then the server must know which subtree changed? Actually, the state change might be localized, but the UI change might propagate? For example, changing a text in a component might only affect that component, but the server might not know that. The server computes the entire UI from the state, so it might send the entire tree.
- Alternatively, we can have the server send a path to the changed node and the new value? But then we need a way to address nodes. We can use keys and paths? That's complex.
Given the simplicity, we stick with sending the entire tree and diffing on the client.
But note: the entire tree might be huge. We can compress the JSON? But still, we are sending the entire tree.
Another idea: the server can send a list of changes (like a patch) but then we need a way to address nodes. We can use keys and parent keys? That's complex and might not be worth it.
So, for now, we design the protocol to send the entire tree.
However, we can optimize by having the server send only the changed part if the client and server agree on a way to identify the root of the changed part? But that's an optimization for later.
5. Summary of the protocol:
code
- The server sends a JSON object representing the root component.
- The root component has:
{
"type": "View",
"props": { ... },
"children": [ ... ] // optional, depends on the component
}
- Every child node (in any parent's children array) must have a "key" property (string) that is unique among its siblings.
- The client validates the entire tree:
- Check that every node's type is in the registry.
- Check that the props match the schema for that type.
- Check that if the component allows children, then the "children" property is an array (or undefined if no children). If the component does not allow children, then "children" must be undefined or an empty array? We can be strict: if the component does not allow children, then "children" must not be present? Or we ignore children? We should ignore or error on unexpected children.
- Check that every child in a parent's children array has a key, and that the keys are unique among the siblings.
- Check resource limits: maximum depth, maximum number of nodes, maximum string length, etc.
- The client then performs a keyed diff (as described) between the old tree and the new tree, and updates the UI.
6. Example:
code
Old tree:
{
"type": "View",
"props": { "style": { "flex": 1 } },
"children": [
{ "type": "Text", "key": "text1", "props": { "text": "Hello" } }
]
}
New tree:
{
"type": "View",
"props": { "style": { "flex": 1 } },
"children": [
{ "type": "Text", "key": "text1", "props": { "text": "Hello World" } },
{ "type": "Text", "key": "text2", "props": { "text": "Goodbye" } }
]
}
Diff:
- The root (View) type and props are the same, so we update the root's props (none changed? actually, the root's props are the same, so no change? But we do check and update if changed).
- Then for the root's children:
oldChildren: [ {key: 'text1', ...} ]
newChildren: [ {key: 'text1', ...}, {key: 'text2', ...} ]
We see:
- 'text1' exists in both: update the Text component with key 'text1' (change the text prop).
- 'text2' is new: add a new Text component.
- No old child left, so no removal.
Result: update the text of the first Text and add the second Text.
7. Handling of root replacement:
code
If the root type changes, then we replace the entire tree.
8. Component registry:
code
The client has a registry like:
const componentRegistry = {
'View': {
props: { style: { type: 'object', required: false } },
hasChildren: true
},
'Text': {
props: { text: { type: 'string', required: true }, style: { type: 'object', required: false } },
hasChildren: false
},
// ... other components
}
During validation, for each node, we look up the component by type and then check:
- All required props are present and of the correct type.
- All provided props are allowed (no extra props? We can ignore extra props or error? We should error on extra props to catch mistakes).
- If the component does not have children, then the node must not have a children property (or we ignore it? We should error to catch mistakes).
Also, we check the key: if the node has a parent (i.e., it is in a children array), then it must have a key.
9. Error handling:
code
If validation fails, the client should:
- Log the error (for debugging).
- Not update the UI? Or fall back to a safe state? We can keep the old UI and not apply the new tree.
We don't want to crash the app.
10. Extensibility:
code
We can add new component types by updating the client and server at the same time? But if the server sends a new component type that the client doesn't know, we error.
So, the client must be updated to support new components.
11. Binary format:
code
For efficiency, we might want to use a binary format (like Protocol Buffers) instead of JSON. But the design is the same.
12. Versioning:
code
13. Conclusion:
code
14. Edge cases:
code
- What if the server sends a node with a key that already exists in the same parent? We validate and reject? Or we generate a new key? We should reject because it's a server error.
- What if the server sends a node without a key? We reject.
- What if the server sends a node with a key that is not a string? We reject.
- What if the server sends a node with a children array that has a cycle? Actually, we are traversing the tree recursively, so we would have infinite recursion. We must set a maximum depth and also check for cycles? But in a tree (as a nested structure) there are no cycles. However, if the server uses the same object reference in two places? In JSON, you cannot have the same object in two places because JSON doesn't support references. So we are safe.
But if we use a binary format that allows references? We are not. We are sending a tree as a nested structure.
So, we are safe from cycles.
- What if the server sends a very deep tree? We set a maximum depth (like 100) and reject if exceeded.
- What if the server sends a very wide tree (many children for a node)? We set a maximum number of children per node? Or a total node count? We can set both.
15. Implementation:
code
The client:
- Has a componentRegistry: Map<type, ComponentSchema>
- Has a currentTree (the last rendered tree) or null.
- When a new tree arrives:
validateTree(newTree, componentRegistry, limits) // returns an error if invalid.
if (valid) {
if (currentTree) {
diffAndUpdate(currentTree, newTree)
} else {
renderTree(newTree)
}
currentTree = newTree
} else {
// handle error, maybe keep currentTree
}
- diffAndUpdate(oldNode, newNode) {
if (oldNode.type !== newNode.type) {
// replace entire subtree
replaceSubtree(oldNode, newNode)
} else {
// update props
updateProps(oldNode, newNode.props)
// diff children
if (oldNode.children || newNode.children) {
const oldChildren = oldNode.children || []
const newChildren = newNode.children || []
// Build map of old children by key
const oldChildrenByKey = new Map()
for (const child of oldChildren) {
if (oldChildrenByKey.has(child.key)) {
// duplicate key in oldChildren? This shouldn't happen because we validated, but just in case.
// We can take the first one? Or error? We already validated, so we assume no duplicates.
}
oldChildrenByKey.set(child.key, child)
}
const newChildrenArray = []
for (const newChild of newChildren) {
const oldChild = oldChildrenByKey.get(newChild.key)
if (oldChild) {
diffAndUpdate(oldChild, newChild)
newChildrenArray.push(oldChild) // oldChild is now updated
oldChildrenByKey.delete(newChild.key)
} else {
const created = createNode(newChild)
newChildrenArray.push(created)
}
}
// Now, oldChildrenByKey has the old children that were not in newChildren -> remove them.
for (const oldChild of oldChildrenByKey.values()) {
removeNode(oldChild)
}
// Now, set the children of the current node to newChildrenArray? But note: the order is the order of newChildren.
// We already have the updated oldChild nodes in the array, and the new created nodes.
// So we set the current node's children to newChildrenArray.
setChildren(oldNode, newChildrenArray)
}
}
}
Note: we are mutating the old tree? Actually, we are updating the old tree in place? Or we create a new tree? We need to update the rendered UI, so we need to update the actual UI components.
In practice, we might have a virtual tree that represents the rendered UI, and we update that virtual tree and then sync with the actual UI.
But the idea is the same.
16. Performance:
code
The diffing algorithm is O(n) for the children of each node, and we do it for every node. So overall O(N) where N is the number of nodes.
But note: we are rebuilding the children array for every node that has children. That's acceptable.
However, if the tree is very large, we might want to avoid rebuilding the entire children array if only a few children changed? But we are already doing a keyed diff, so we only change the nodes that are added, removed, or updated. But we are creating a new array for the children? Yes, but that's O(n) for each node.
We can try to optimize by only changing the order if necessary? Actually, when we build the newChildrenArray, we are using the order of newChildren. So if the order changes, we reorder.
But note: the oldChild nodes that are kept are the same objects? We are pushing the oldChild (which we updated) into the new array. So we are reordering the array.
That's fine.
17. Conclusion:
code
18. Final protocol message:
code
{
"tree": { ... } // the root node
}
We can add a version later if needed.
So, the entire message is just the tree? But the root node is an object with type, props, children, and no key? Actually, the root node doesn't have a key, so we don't send a key for the root.
Example:
{
"type": "View",
"props": { "style": { "flex": 1 } },
"children": [
{
"type": "Text",
"key": "text1",
"props": { "text": "Hello" }
}
]
}
This is the entire message.
19. Binary format:
code
We can define a binary format using something like Protocol Buffers or FlatBuffers. But that's an implementation detail.
The design remains the same.
20. Conclusion:
code
We have designed a server-driven UI protocol that:
- Uses a tree of components with keys for efficient diffing.
- Validates the tree against a component registry and resource limits for safety.
- Diffs the new tree with the old tree using a keyed diff algorithm and updates the UI.
This should be a good starting point.</think>
I'll design a comprehensive server-driven UI protocol that addresses templates, diffing, and safety. This protocol balances flexibility with performance and security.
Protocol: SDUI v1.0 (Server-Driven UI)
1. Core Principles
Declarative: Server describes what to show, not how
Efficient: Minimize data transfer and client processing
Safe: Sandboxed execution, validation, and resource limits
// Client advertises support
{
"supported_versions": ["1.0", "0.9"],
"fallback": "rest_json" // Can fallback to simpler format
}
// Server responds with highest common version
10.2 Backward Compatibility Rules
Additive Changes Only: New props/components must be optional
// All random values must come from server with seed:
{
"t": "placeholder_image",
"p": {
"seed": "user123_142", // Deterministic
"width": 200,
"height": 200
}
}
12. Summary of Key Innovations
Keyed Diffing with Sibling Scope: Efficient updates without full re-render
Multi-Layer Validation: Schema + resources + CSP
Action Registry Sandbox: No arbitrary code execution
Template Variables with Filters: Safe data interpolation
Resource Quotas: Prevent DoS via large/complex trees
Context Isolation: Session-scoped variables
13. When to Use Full Tree vs Patches
Scenario
Recommendation
Initial load / Screen change
Full tree
Small updates (<10% of nodes)
Patches
List pagination
Full tree + stream token
Real-time collaborative editing
Operational transforms (beyond v1)
A/B testing variations
Full tree with experiment flags
This protocol provides:
Safety: Multiple validation layers, sandboxing
Performance: Keyed diffing, incremental updates
Flexibility: Template system with constraints
Debugging: Sequence numbers, dev tools
Evolution: Versioning, backward compatibility
The key insight is treating server-driven UI as data, not code, with the client maintaining ultimate control over what gets rendered and how.
Server sends: a tree of nodes, each node has:
- type (string)
- key (string, required for all nodes that are part of a list? Actually, for all nodes that are children of a parent that has multiple children? But to be safe, we can require keys for all nodes? But then the root might not have a key? We can have the root without a key? Or we can have a key for every node, including the root? Let's require keys for all nodes that are in a list (i.e., have siblings). For single children, we don't need a key? But then moving from a single child to a list? It's simpler to require keys for every node that is not the root? Actually, the root can have a key too? But the root is the whole tree, so we can have a key for the root? Not necessary.
Alternatively, we can have:
The server sends a tree with:
- type (for the root and every node)
- props
- children (array)
- key (optional, but if present, must be unique among siblings)
Then the client does a keyed diff for every parent's children.
But what about nodes without keys? They are matched by index? We can do:
For a parent's children:
- If the new children have keys, then we use keys to match.
- If any child in the new children doesn't have a key, then we fall back to index-based matching for all? Or only for those without keys? Actually, React requires that if you use keys, all siblings must have keys. So we can enforce that.
Let's enforce: for any parent that has more than one child, all children must have keys. For a single child, key is optional.
But then moving a single child to a parent with multiple children? The single child might not have a key, then when moved, it will be treated as a new node? So we should require keys for all nodes that are ever going to be in a list? That is, if a node can ever be one of multiple siblings, it must have a key. But the server might not know? So we can require the server to always assign keys to every node that is not the root? Actually, the root is the whole tree, so it doesn't have siblings. So we can require keys for all nodes except the root? But then if we have two roots? We have one root.
Let's simplify: every node in the tree (except the root) must have a key if it has siblings? That's messy.
Better: require keys for every node that is a child (i.e., not the root) and if a parent has multiple children, then all children must have keys. And if a parent has a single child, the child may or may not have a key? But then when we add a second child, the first child (without key) will be matched by index? And then when we remove the second child, the first child (without key) will be at index 0? But if we had two children with keys, then the first child (with key) is matched by key.
Alternatively, we can require keys for all children of a parent, regardless of the number of children. Then we don't have to worry about index-based matching.
So:
- The root node does not need a key (because it has no siblings).
- Every other node (that is a child of some parent) must have a key.
- The key must be unique among the children of the same parent.
Then the diffing algorithm for a parent's children:
oldChildren: array of old child nodes (each has a key)
newChildren: array of new child nodes (each has a key)
We create a map of oldChildren by key.
Then for each newChild in newChildren:
if oldChild with same key exists, then update that node (and its subtree) and remove it from the map.
else, create a new node.
Then, for any remaining oldChild in the map (which means they were in the oldChildren but not in newChildren), remove them.
This works for moves because the key is unique among siblings, but note: if a node moves to a different parent, then in the new parent's children we have the key, and in the old parent's children we remove it. So it's a removal and an addition.
But what if the same key appears in two different parents? That's not allowed because keys must be unique among siblings. So if a node moves, it gets a new parent and then its key is now among the new parent's children. The old parent's children no longer have that key.
So this works.
However, note: the key must be stable for the same logical component across renders. The server must assign the same key to the same logical component even if it moves? Actually, if it moves, it's a different parent, so the key is only unique among siblings. So the same key can be reused in a different parent? But then if we have two nodes with the same key in different parents, that's fine because they are not siblings.
But what if we have:
Parent1: [ {key: 'a'}, {key: 'b'} ]
Parent2: [ {key: 'a'} ]
Then we remove Parent1 and add Parent2? Actually, the trees are separate. So when we diff, we are diffing each parent's children separately.
So the key only needs to be unique among the children of the same parent.
So, the client must:
code
- Have a registry of component types (with their prop schemas).
- When receiving a tree, traverse it and for each node:
- Check that the type is in the registry.
- Check that the props (if any) match the schema for that type.
- Check that if the node has children, then it is a component that can have children? Actually, some components might not have children. So the schema should also specify if children are allowed.
- Check the key: if the node is not the root, then it must have a key, and within the same parent, keys must be unique.
- Also, check the overall tree size and depth.
Additionally, we must consider:
code
- The server might send a key that is too long? We can set a maximum key length.
- The server might send a prop value that is too large (like a very long string). We can set limits on string lengths, array lengths, etc.
So, safety is about validating the incoming tree against a schema and resource limits.
Step 1: Client and server agree on a set of component types (with their prop schemas and whether they can have children). This is out-of-band (built into the client app).
Step 2: The server sends a UI update as a JSON object (or binary, but let's assume JSON for simplicity) representing the root node of the tree.
Step 3: The client validates the entire tree (recursively) against the component registry and resource limits.
Step 4: The client performs a diff between the old tree (if any) and the new tree, using the following algorithm:
function diff(oldTree, newTree):
if oldTree.type != newTree.type:
// Different component types, replace entire subtree.
// But note: we are at the root? Actually, we start at the root.
// For the root, we don't have a key, so we just replace.
// But for children, we use keys.
// So we need to handle the root separately? Actually, the root is the whole tree, so we replace the whole tree if the root type changes? But the root type is fixed (like 'View' or 'Fragment')? Actually, the root can be any component? Let's assume the root is a single component (like a View). Then if the root type changes, we replace the entire tree.
However, in our keyed diff, we don't compare the root by key because the root has no siblings. So we compare the root by type? Actually, the root is a single node. So if the root type changes, we replace the entire tree.
But note: the root might have children. So we diff the root's children by key, and also update the root's props.
So, algorithm for a node (with children):
if (oldNode.type !== newNode.type) {
// Replace the entire subtree.
// But note: the root node might be replaced, then we throw away the entire old tree and build a new one.
} else {
// Update the props of the current node.
// Then, for the children:
if (oldNode.children && newNode.children) {
// Both have children, so we diff the children arrays.
diffChildren(oldNode.children, newNode.children);
} else if (oldNode.children) {
// oldNode has children but newNode doesn't: remove all children.
} else if (newNode.children) {
// newNode has children but oldNode doesn't: add all new children.
}
}
But wait, we are using keys for children. So for children, we do:
diffChildren(oldChildren, newChildren) {
const oldByKey = map(oldChildren, child => child.key);
const newByKey = map(newChildren, child => child.key);
// For each newChild, if oldByKey has the same key, then diff that child (recursively) and remove from oldByKey.
// For each remaining oldChild in oldByKey, remove.
// Also, note: the order of children matters? In a flex layout, order matters. So we must also account for order? Actually, in keyed diff, the order of children is determined by the order in the newChildren array. So if a child with key 'a' was at index 0 and now at index 1, we move it? But our diff by key doesn't care about index, it just matches by key. Then when we update, we update the node and then we reorder the children? Actually, the client's tree structure is a tree of nodes, and each node has an ordered list of children. So when we match by key, we are matching the logical component, and then we update its position in the parent's children array to the new index.
So, in the parent, we rebuild the children array by:
newChildrenArray = []
for each newChild in newChildren:
if oldChildWithSameKey exists:
diff(oldChildWithSameKey, newChild)
newChildrenArray.push(updatedChild)
else:
create new node for newChild and push.
Then, for any oldChild not matched, they are removed.
So the order is taken from the newChildren array.
}
But note: what about nodes without keys? We said we require keys for all children? So we assume all children have keys.
However, what if the server sends a child without a key? We can treat it as an error? Or we can generate a key for it? But then if the same node (without key) appears in the next render, we won't be able to match it because we generated a key? So we should require keys for all children.
But the root node doesn't have a key? Actually, the root node is not a child, so it doesn't need a key. But the root node's children must have keys.
So, in the diffChildren function, we assume every child has a key.
But what if the server sends a child without a key? We can assign a temporary key (like index) but then if the server sends the same node again without a key, we won't match? So we should validate and require keys for all children.
So, during validation, we check that every child (of any parent) has a key.
Step 5: The client applies the diff to the current UI tree and updates the rendered UI.
We might want to version the protocol. We can have a version number in the message? But if we change the protocol, we break old clients.
So, we can have a version in the handshake? Or in every message? Let's assume we start with version 1 and then if we change, we increment.
But note: the component registry changes? That's out-of-band.
So, the protocol itself (the structure of the tree) is versioned. We can have:
{
"version": 1,
"tree": { ... }
}
Then the client can check the version and if it doesn't support, it can ignore.
But the component registry is tied to the app version, not the protocol version.
So, we might not need a protocol version if we design it to be extensible? For example, we can add new fields and ignore unknown fields? But in our case, we have a strict schema for each component.
Alternatively, we can have a version for the entire message and then the client can decide how to parse.
Let's not overcomplicate: we assume the client and server are updated together? In practice, the server is controlled by the same team as the client, so they can update together.
But if we have a native app that updates from an app store and the server is independent, then we need to handle versioning.
So, we can have:
{
"protocolVersion": 1,
"tree": { ... }
}
And the client must support the protocolVersion. If the client sees a higher version, it can reject.
But note: the component registry is part of the client, so if the server sends a new component type that the client doesn't know, it's an error.
So, we have two versionings:
- Protocol version: the structure of the message (like the tree format).
- Component registry version: the set of components and their schemas.
We can combine them? Or we can have the protocol version and then the tree uses the component registry of that protocol version? Actually, the component registry is not part of the protocol, it's part of the app.
So, the protocol version only covers the structure of the message (like the tree format). The component registry is fixed for a given app version.
Therefore, when we change the component registry, we are changing the app, and we update the client and server together.
So, we don't need to version the protocol if we are sure that the client and server are updated together? But we might have old clients that don't get updated? Then we need to support backward compatibility.
This is a deployment issue.
For the protocol design, we can design it to be extensible:
- We allow unknown fields in the node? Actually, we don't because we validate against the schema. So if we add a new prop to a component, the old client will reject the new prop? We can have the schema specify that extra props are allowed? But then the old client will ignore the new prop? That might be acceptable.
- We can have the schema for a component include a pattern for additional props? Or we can have a flag "allowExtraProps". But then the old client might break if we add a required prop? Because the old client doesn't know about the required prop and will fail validation.
So, we must be careful when changing the component registry.
We can use a versioning for the component registry? But then the server must know which version the client supports? That's complex.
Alternatively, we can design the components to be backward compatible:
- When adding a new prop, make it optional and with a default value.
- When removing a prop, stop sending it, and the old client will ignore it? But if the old client requires that prop, then it breaks.
So, we must design the component registry to be additive and never remove or change required props? That's a constraint.
Given the complexity, we assume that the client and server are updated together, and we don't have to support old clients with new servers or vice versa.
Therefore, we don't version the protocol.
We design the protocol as:
The server sends a JSON object representing the root node of the UI tree.
Each node has:
- type: string (required)
- props: object (optional, defaults to {})
- children: array of nodes (optional, defaults to [])
- key: string (required for all nodes that are children of a parent, i.e., not the root)
The client validates the tree against a component registry (which defines allowed types, their props, and whether they can have children).
The client then diffs the new tree with the old tree (if any) using a keyed diff algorithm (for children of each parent) and updates the UI.
The client must enforce resource limits (depth, node count, etc.) during validation.
This design is simple and stateless on the server.
However, note: the server must assign stable keys to logical components across renders. The server must have a way to generate keys that are stable for the same logical component even if the component moves? Actually, the key only needs to be unique among siblings. But if a component moves, it gets a new parent, so the key can be the same? Yes, because the key is only unique among siblings. So if a component moves from parent A to parent B, then in parent A's children we remove the key, and in parent B's children we add the same key. That's fine.
But what if we have two instances of the same component in different parts of the tree? They can have the same key? Yes, because they are in different parents.
So, the server must assign keys that are unique among siblings, but can be reused across different parents.
Example:
Parent1: [ {key: 'a', type: 'Text', ...}, {key: 'b', type: 'Text', ...} ]
Parent2: [ {key: 'a', type: 'Text', ...} ]
This is allowed because the two 'a' keys are in different parents.
So, the server can use a simple key generation: for each logical component, assign a unique id (across the entire UI) and then use that as the key? But then we are guaranteed uniqueness across the entire tree? Actually, if we use a globally unique id, then we don't have to worry about duplicate keys in the same parent? But we still have to check because the server might make a mistake? So we validate.
But note: the key only needs to be unique among siblings. So the server can use the same key for two components that are not siblings? That's allowed. But if by mistake they become siblings, then we have duplicate keys. So we validate.
So, the server can use any scheme as long as within a parent's children, keys are unique.
But to make it easy, the server can use a globally unique id for every logical component. Then we are safe.
However, the server might not want to generate a globally unique id? It can use the index in the array? But then if the order changes, the key changes? That would break the diff because we match by key. So the key must be stable for the same logical component even if it moves or the order of siblings changes.
Therefore, the server must assign a stable key to each logical component that does not depend on its position in the tree.
So, the server should have a way to assign a stable id to each component instance. For example, if the component represents a user in a list, then the user id can be the key.
So, the key is the stable identifier for the component instance.
This is similar to React's key.
So, the server must use a stable, unique (among siblings) key for each component instance.
This is a requirement for the server.
This design should work for a server-driven UI protocol.
We have:
- A tree structure with typed nodes and props.
- Keys for efficient diffing.
- Validation for safety.
- Diffing algorithm that uses keys to match nodes and updates the UI accordingly.
We assume the server sends the entire tree on every update.
We can later optimize by sending only the changed subtree if we can address nodes by key and parent key? But that's an extension.
Let's write a simple example of the protocol in action.
Example:
Client current tree:
View
|
+-- Text (key: 'hello', text: 'Hello')
Server sends:
View
|
+-- Text (key: 'hello', text: 'Hello World')
+-- Text (key: 'goodbye', text: 'Goodbye')
The client:
- Validates: both Text nodes have keys, and the root View is known, and Text is known and doesn't allow children? Actually, Text doesn't allow children, and we don't have children for Text.
- Diffs the root's children:
oldChildren: [ {key: 'hello', ...} ]
newChildren: [ {key: 'hello', ...}, {key: 'goodbye', ...} ]
For 'hello': update the Text node's text prop.
For 'goodbye': create a new Text node.
Then set the root's children to [ updated 'hello', new 'goodbye' ].
- The UI updates: the first Text now says "Hello World", and a new Text saying "Goodbye" appears.
This works.
Now, if the server sends:
View
|
+-- Text (key: 'goodbye', text: 'Goodbye')
+-- Text (key: 'hello', text: 'Hello World')
Then the order changes. The client will:
oldChildrenByKey: { 'hello' -> oldText1 }
newChildren:
first: {key: 'goodbye', ...} -> not in oldChildrenByKey, so create new.
second: {key: 'hello', ...} -> in oldChildrenByKey, so update and push.
Then newChildrenArray: [ newText (goodbye), updatedText (hello) ]
Then we remove any old children left in oldChildrenByKey? None.
So the root's children array becomes [ newText, updatedText ].
So the order is changed.
This is correct.
Now, if the server sends:
View
|
+-- Text (key: 'hello', text: 'Hello World')
Then we remove the 'goodbye' node and update 'hello'.
This is correct.
Now, if the server sends:
View
|
+-- Text (key: 'hello', text: 'Hello World')
+-- Text (key: 'hello', text: 'Goodbye') // duplicate key!
Then during validation, we would see that the parent (View) has two children with the same key 'hello'. We should reject the entire tree.
So, the validation step catches this.
Similarly, if a child node doesn't have a key, we reject.
This design seems solid.
Let's write the validation algorithm:
function validateNode(node, parent, componentRegistry, limits, depth) {
if (depth > limits.maxDepth) {
throw new Error('Max depth exceeded')
}
// Check type
if (!componentRegistry[node.type]) {
throw new Error(`Unknown component type: ${node.type}`)
}
const schema = componentRegistry[node.type]
// Check props
for (const prop in node.props) {
if (!schema.props[prop]) {
throw new Error(`Unexpected prop: ${prop} for component ${node.type}`)
}
// Check type of prop? We can do runtime type checking? Or we trust the server? We should check.
// But for simplicity, we assume the server sends the correct types. However, for safety, we should check.
// We can have a type system: 'string', 'number', 'boolean', 'object', 'array', etc.
// We skip for now, but in production we would check.
}
// Check required props
for (const prop in schema.props) {
if (schema.props[prop].required && node.props[prop] === undefined) {
throw new Error(`Missing required prop: ${prop} for component ${node.type}`)
}
}
// Check children
if (schema.hasChildren) {
if (node.children) {
if (!Array.isArray(node.children)) {
throw new Error(`Children must be an array for component ${node.type}`)
}
// Check each child
const childKeys = new Set()
for (const child of node.children) {
if (typeof child.key !== 'string') {
throw new Error(`Child must have a key for component ${node.type}`)
}
if (childKeys.has(child.key)) {
throw new Error(`Duplicate key ${child.key} in children of ${node.type}`)
}
childKeys.add(child.key)
validateNode(child, node, componentRegistry, limits, depth+1)
}
}
} else {
if (node.children && node.children.length > 0) {
throw new Error(`Component ${node.type} does not support children`)
}
}
}
We also need to check the root node: the root node doesn't have a parent, so we don't check for key? Actually, the root node doesn't need a key.
So, in the validateNode function, we don't check for key if the node is the root? But we are passing the parent. For the root, parent is null.
We can adjust:
if (parent) {
if (typeof node.key !== 'string') {
throw new Error(`Child node must have a key`)
}
}
But note: the root node might have a key? We said the root doesn't need a key. So we can allow the root to have a key? But it's not used. So we can ignore the root's key? Or we can require the root not to have a key? Let's not require the root to have a key.
So, in validateNode:
if (parent && typeof node.key !== 'string') {
throw new Error(`Child node must have a key`)
}
And then for the root, parent is null, so we skip.
Also, we must check the total number of nodes? We can count during validation and throw if exceeds limits.maxNodes.
We can pass a counter by reference.
Alternatively, we can do a separate count.
But for simplicity, we can do:
let nodeCount = 0
function validateNode(...) {
nodeCount++
if (nodeCount > limits.maxNodes) {
throw new Error('Too many nodes')
}
... rest ...
}
But note: we are traversing recursively, so we count every node.
This is acceptable.