-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSbmdHandlerInvoker.cpp
More file actions
467 lines (390 loc) · 17.6 KB
/
Copy pathSbmdHandlerInvoker.cpp
File metadata and controls
467 lines (390 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//------------------------------ tabstop = 4 ----------------------------------
//
// If not stated otherwise in this file or this component's LICENSE file the
// following copyright and licenses apply:
//
// Copyright 2026 Comcast Cable Communications Management, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
//
//------------------------------ tabstop = 4 ----------------------------------
/*
* Created by tlea on 6/12/2026
*/
#define LOG_TAG "SbmdHandlerInvoker"
#define logFmt(fmt) "(%s): " fmt, __func__
#include "SbmdHandlerInvoker.h"
#include "MQuickJsRuntime.h"
#include "SbmdResultExecutor.h"
#include "SbmdWireContract.h"
#include "matter/sbmd/SafeJSValue.h"
#include <string>
#include <variant>
extern "C" {
#include <cjson/cJSON.h>
#include <icLog/logging.h>
#include <mquickjs/mquickjs.h>
}
// Forward-declare C APIs used by ExecuteOps. These are provided by the
// main build but not available in unit tests. The test build stubs them.
extern "C" {
extern void updateResource(const char *deviceUuid,
const char *endpointId,
const char *resourceId,
const char *newValue,
void *metadata);
extern void setMetadata(const char *deviceUuid, const char *endpointId, const char *name, const char *value);
extern bool deviceServiceSetMetadata(const char *uri, const char *value);
}
namespace barton
{
SafeJSValue SbmdHandlerInvoker::BuildBaseArgs(JSContext *ctx, const HandlerContext &hctx)
{
// Root args for the whole build: subsequent allocations (JS_NewString, JS_NewObject)
// may trigger the mquickjs moving GC, which would otherwise sweep the unrooted args.
SafeJSValue args {ctx, JS_NewObject(ctx)};
args.SetString(SBMD_KEY_DEVICE_UUID, hctx.deviceUuid.c_str());
args.SetString(SBMD_KEY_ENDPOINT_ID, hctx.endpointId.c_str());
// clusterFeatureMaps is created-and-attached atomically, then populated through the
// reachable child node.
SafeJSValue featureMaps = args.AddObject(SBMD_KEY_CLUSTER_FEATURE_MAPS);
for (const auto &[clusterId, featureMap] : hctx.clusterFeatureMaps)
{
featureMaps.SetUint32(std::to_string(clusterId).c_str(), featureMap);
}
return args;
}
SafeJSValue SbmdHandlerInvoker::BuildAttributeArgs(JSContext *ctx,
const HandlerContext &hctx,
uint32_t clusterId,
uint32_t attributeId,
const std::string &tlvBase64)
{
SafeJSValue args = BuildBaseArgs(ctx, hctx);
SafeJSValue trigger = args.AddObject(SBMD_KEY_ATTRIBUTE);
trigger.SetUint32(SBMD_KEY_CLUSTER_ID, clusterId);
trigger.SetUint32(SBMD_KEY_ATTRIBUTE_ID, attributeId);
if (!tlvBase64.empty())
{
trigger.SetString(SBMD_KEY_TLV_BASE64, tlvBase64.c_str());
}
return args;
}
SafeJSValue SbmdHandlerInvoker::BuildEventArgs(JSContext *ctx,
const HandlerContext &hctx,
uint32_t clusterId,
uint32_t eventId,
const std::string &tlvBase64)
{
SafeJSValue args = BuildBaseArgs(ctx, hctx);
SafeJSValue trigger = args.AddObject(SBMD_KEY_EVENT);
trigger.SetUint32(SBMD_KEY_CLUSTER_ID, clusterId);
trigger.SetUint32(SBMD_KEY_EVENT_ID, eventId);
if (!tlvBase64.empty())
{
trigger.SetString(SBMD_KEY_TLV_BASE64, tlvBase64.c_str());
}
return args;
}
SafeJSValue SbmdHandlerInvoker::BuildCommandArgs(JSContext *ctx,
const HandlerContext &hctx,
uint32_t clusterId,
uint32_t commandId,
const std::string &tlvBase64)
{
SafeJSValue args = BuildBaseArgs(ctx, hctx);
SafeJSValue trigger = args.AddObject(SBMD_KEY_COMMAND);
trigger.SetUint32(SBMD_KEY_CLUSTER_ID, clusterId);
trigger.SetUint32(SBMD_KEY_COMMAND_ID, commandId);
if (!tlvBase64.empty())
{
trigger.SetString(SBMD_KEY_TLV_BASE64, tlvBase64.c_str());
}
return args;
}
SafeJSValue SbmdHandlerInvoker::BuildResourceArgs(JSContext *ctx,
const HandlerContext &hctx,
const std::string &resourceId,
const std::optional<std::string> &input)
{
SafeJSValue args = BuildBaseArgs(ctx, hctx);
SafeJSValue resource = args.AddObject(SBMD_KEY_RESOURCE);
resource.SetString(SBMD_KEY_RESOURCE_ID, resourceId.c_str());
if (input.has_value())
{
resource.SetString(SBMD_KEY_INPUT, input->c_str());
}
else
{
resource.SetNull(SBMD_KEY_INPUT);
}
return args;
}
std::optional<ParsedResult>
SbmdHandlerInvoker::InvokeHandler(JSContext *ctx, JSValue handler, const SafeJSValue &args)
{
// Root the handler function: JS_StackCheck below may allocate (grow the JS stack) and the
// moving GC would then relocate an unrooted handler, leaving the pushed argument stale.
SafeJSValue handlerRooted(ctx, handler);
if (JS_IsUndefined(handlerRooted.Get()))
{
icError("handler is undefined");
return std::nullopt;
}
if (JS_StackCheck(ctx, 3)) // args, handler, this
{
icError("stack overflow before handler call");
return std::nullopt;
}
// Stack order for JS_Call: arg, func, this
JS_PushArg(ctx, args.Get());
JS_PushArg(ctx, handlerRooted.Get());
JS_PushArg(ctx, JS_NULL);
// Arm the execution timeout
MQuickJsRuntime::SetDeadline(std::chrono::steady_clock::now() + std::chrono::milliseconds(5000));
JSValue result = JS_Call(ctx, 1);
MQuickJsRuntime::ClearDeadline();
if (JS_IsException(result))
{
std::string err;
MQuickJsRuntime::CheckAndClearPendingException(ctx, &err);
icError("handler threw exception: %s", err.c_str());
return std::nullopt;
}
return SbmdResultExecutor::Parse(ctx, result);
}
FetchedSupplements SbmdHandlerInvoker::PrefetchSupplements(const SbmdSupplements &supplements,
const AttributeSupplementFetcher &attrFetcher,
const ResourceSupplementFetcher &resFetcher,
const PersistentDataFetcher &persistFetcher,
const TransientDataFetcher &transientFetcher)
{
FetchedSupplements fetched;
for (const auto &aliasName : supplements.attributes)
{
fetched.attributes.push_back({aliasName, attrFetcher(aliasName)});
}
for (const auto &path : supplements.resources)
{
fetched.resources.push_back({path, resFetcher(path)});
}
for (const auto &key : supplements.persistentData)
{
fetched.persistentData.push_back({key, persistFetcher(key)});
}
for (const auto &key : supplements.transientData)
{
fetched.transientData.push_back({key, transientFetcher(key)});
}
return fetched;
}
void SbmdHandlerInvoker::AddSupplements(JSContext *ctx,
SafeJSValue &args,
const SbmdSupplements &declared,
const FetchedSupplements &fetched)
{
// Contract: every supplement a driver DECLARES is materialized as a JS property on
// args.supplements at handler invocation. The declaration -- not the fetched data --
// is the source of truth, so a declared key is always defined: it holds the fetched
// value when available, otherwise null. This holds even when the prefetch was skipped
// (e.g. no device) or a fetch bug failed to populate it. Categories and keys that were
// not declared are omitted.
bool anyDeclared = !declared.attributes.empty() || !declared.resources.empty() ||
!declared.persistentData.empty() || !declared.transientData.empty();
if (!anyDeclared)
{
return;
}
// Nested nodes are created-and-attached atomically via AddObject, then populated
// through the reachable child. args is already a SafeJSValue owned by the caller.
SafeJSValue supObj = args.AddObject(SBMD_KEY_SUPPLEMENTS);
auto populate = [](SafeJSValue &parent,
const char *categoryKey,
const std::vector<std::string> &declaredKeys,
const std::vector<FetchedSupplement> &fetchedEntries) {
if (declaredKeys.empty())
{
return;
}
SafeJSValue obj = parent.AddObject(categoryKey);
for (const auto &declaredKey : declaredKeys)
{
const std::string *value = nullptr;
for (const auto &entry : fetchedEntries)
{
if (entry.key == declaredKey && entry.value.has_value())
{
value = &entry.value.value();
break;
}
}
if (value != nullptr)
{
obj.SetString(declaredKey.c_str(), value->c_str());
}
else
{
obj.SetNull(declaredKey.c_str());
}
}
};
populate(supObj, SBMD_KEY_ATTRIBUTES, declared.attributes, fetched.attributes);
populate(supObj, SBMD_KEY_RESOURCES, declared.resources, fetched.resources);
populate(supObj, SBMD_KEY_PERSISTENT_DATA, declared.persistentData, fetched.persistentData);
populate(supObj, SBMD_KEY_TRANSIENT_DATA, declared.transientData, fetched.transientData);
}
void SbmdHandlerInvoker::ExecuteOps(const HandlerContext &hctx,
const std::vector<ResultOp> &ops,
const TransientDataSetter &transientSetter)
{
for (const auto &op : ops)
{
if (std::holds_alternative<ResultOp::UpdateResource>(op.data))
{
const auto &ur = std::get<ResultOp::UpdateResource>(op.data);
// If the op names an endpoint, update that endpoint resource; otherwise the update
// targets a device-level resource (see updateResource: a null endpoint is the
// device root).
const char *epId = ur.endpoint.has_value() ? ur.endpoint->c_str() : nullptr;
cJSON *meta = nullptr;
if (ur.metadata.has_value())
{
meta = cJSON_Parse(ur.metadata->c_str());
}
updateResource(hctx.deviceUuid.c_str(), epId, ur.resource.c_str(), ur.value.c_str(), meta);
if (meta != nullptr)
{
cJSON_Delete(meta);
}
}
else if (std::holds_alternative<ResultOp::SetMetadata>(op.data))
{
const auto &sm = std::get<ResultOp::SetMetadata>(op.data);
setMetadata(hctx.deviceUuid.c_str(), nullptr, sm.name.c_str(), sm.value.c_str());
}
else if (std::holds_alternative<ResultOp::SetPersistentData>(op.data))
{
const auto &sp = std::get<ResultOp::SetPersistentData>(op.data);
std::string uri = "/devices/" + hctx.deviceUuid + "/metadata/sbmd." + sp.key;
if (!deviceServiceSetMetadata(uri.c_str(), sp.value.c_str()))
{
icError("failed to set persistent data '%s'", sp.key.c_str());
}
}
else if (std::holds_alternative<ResultOp::SetTransientData>(op.data))
{
const auto &st = std::get<ResultOp::SetTransientData>(op.data);
if (transientSetter)
{
transientSetter(st.key, st.value, st.ttlSecs);
}
else
{
icWarn("setTransientData('%s') called but no transient setter provided", st.key.c_str());
}
}
else if (std::holds_alternative<ResultOp::Log>(op.data))
{
const auto &log = std::get<ResultOp::Log>(op.data);
icInfo("sbmd: %s", log.message.c_str());
}
}
}
SafeJSValue SbmdHandlerInvoker::BuildCommandResponseArgs(JSContext *ctx,
const HandlerContext &hctx,
uint32_t clusterId,
uint32_t commandId,
const std::string &tlvBase64,
JSValue handlerContext)
{
// Root handlerContext: the arg-building allocations below can relocate it under the
// moving GC before it is attached.
SafeJSValue handlerContextRooted(ctx, handlerContext);
SafeJSValue args = BuildBaseArgs(ctx, hctx);
SafeJSValue response = args.AddObject(SBMD_KEY_RESPONSE);
response.SetUint32(SBMD_KEY_CLUSTER_ID, clusterId);
response.SetUint32(SBMD_KEY_COMMAND_ID, commandId);
if (!tlvBase64.empty())
{
response.SetString(SBMD_KEY_DATA, tlvBase64.c_str());
}
else
{
response.SetNull(SBMD_KEY_DATA);
}
if (!JS_IsUndefined(handlerContextRooted.Get()))
{
args.SetValue(SBMD_KEY_HANDLER_CONTEXT, handlerContextRooted.Get());
}
else
{
args.SetNull(SBMD_KEY_HANDLER_CONTEXT);
}
return args;
}
SafeJSValue SbmdHandlerInvoker::BuildAttributeReadResponseArgs(JSContext *ctx,
const HandlerContext &hctx,
uint32_t clusterId,
uint32_t attributeId,
const std::string &tlvBase64,
JSValue handlerContext)
{
SafeJSValue handlerContextRooted(ctx, handlerContext);
SafeJSValue args = BuildBaseArgs(ctx, hctx);
SafeJSValue attribute = args.AddObject(SBMD_KEY_ATTRIBUTE);
attribute.SetUint32(SBMD_KEY_CLUSTER_ID, clusterId);
attribute.SetUint32(SBMD_KEY_ATTRIBUTE_ID, attributeId);
attribute.SetString(SBMD_KEY_VALUE, tlvBase64.c_str());
if (!JS_IsUndefined(handlerContextRooted.Get()))
{
args.SetValue(SBMD_KEY_HANDLER_CONTEXT, handlerContextRooted.Get());
}
else
{
args.SetNull(SBMD_KEY_HANDLER_CONTEXT);
}
return args;
}
SafeJSValue SbmdHandlerInvoker::BuildDeferredErrorArgs(JSContext *ctx,
const HandlerContext &hctx,
const std::string &errorType,
const std::string &errorMessage,
int32_t matterCode,
JSValue handlerContext)
{
SafeJSValue handlerContextRooted(ctx, handlerContext);
SafeJSValue args = BuildBaseArgs(ctx, hctx);
SafeJSValue error = args.AddObject(SBMD_KEY_ERROR);
error.SetString(SBMD_KEY_TYPE, errorType.c_str());
error.SetString(SBMD_KEY_MESSAGE, errorMessage.c_str());
if (matterCode >= 0)
{
error.SetInt32(SBMD_KEY_MATTER_CODE, matterCode);
}
else
{
error.SetNull(SBMD_KEY_MATTER_CODE);
}
if (!JS_IsUndefined(handlerContextRooted.Get()))
{
args.SetValue(SBMD_KEY_HANDLER_CONTEXT, handlerContextRooted.Get());
}
else
{
args.SetNull(SBMD_KEY_HANDLER_CONTEXT);
}
return args;
}
} // namespace barton