Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions bindings/js/__test__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { fileURLToPath } from 'node:url'

import {
DynWinRtArray,
DynWinRtDelegate,
DynWinRtMethodSig,
DynWinRtStruct,
DynWinRtType,
Expand Down Expand Up @@ -701,6 +702,30 @@ test('build WinRT types', (t) => {
t.truthy(DynWinRtType.iAsyncOperation(DynWinRtType.object()))
})

test('delegate creation failures are reported as JavaScript errors', (t) => {
const objectType = DynWinRtType.object()
t.throws(
() =>
DynWinRtDelegate.create(
WinGuid.parse('699a62d5-a8a5-431c-9c00-a75c70b30524'),
[objectType, objectType, objectType],
() => {},
),
{ message: /supports up to 2 parameters/ },
)

const emptyStruct = DynWinRtType.structType('DynWinRT.Tests.EmptyDelegateArgument', [])
t.throws(
() =>
DynWinRtDelegate.create(
WinGuid.parse('f1662550-78fd-4bf1-9022-0a2c85168380'),
[objectType, emptyStruct],
() => {},
),
{ message: /struct callbacks do not support/ },
)
})

test('invoke WinRT through dynamic metadata', (t) => {
roInitialize(1)
const factoryIid = WinGuid.parse('44a9796f-723e-4fdf-a218-033e75b0c084')
Expand Down Expand Up @@ -1162,3 +1187,43 @@ test('progress callbacks do not keep Node alive after completion', async (t) =>
t.is(code, 0, stderr)
t.regex(stdout, /progress-exit-ok/)
})

test('struct progress callbacks retain nested interface values', async (t) => {
const child = spawn(process.execPath, [fileURLToPath(new URL('./struct-progress-child.mjs', import.meta.url))], {
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
})

let stdout = ''
let stderr = ''
child.stdout.setEncoding('utf8')
child.stderr.setEncoding('utf8')
child.stdout.on('data', (chunk) => {
stdout += chunk
})
child.stderr.on('data', (chunk) => {
stderr += chunk
})

let timedOut = false
const timeout = setTimeout(() => {
timedOut = true
child.kill()
}, 20_000)
t.teardown(() => {
clearTimeout(timeout)
if (child.exitCode === null && child.signalCode === null) {
child.kill()
}
})

const code = await new Promise<number | null>((resolve, reject) => {
child.once('error', reject)
child.once('close', resolve)
})
clearTimeout(timeout)

t.false(timedOut, 'struct progress child timed out')
t.is(code, 0, stderr)
t.regex(stdout, /struct-progress-ok/)
})
124 changes: 124 additions & 0 deletions bindings/js/__test__/struct-progress-child.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import assert from 'node:assert/strict'
import { createServer } from 'node:http'

import { DynWinRtMethodSig, DynWinRtType, DynWinRtValue, WinGuid, roInitialize } from '../dist/winrt.js'

roInitialize(1)

const uriFactoryIid = WinGuid.parse('44a9796f-723e-4fdf-a218-033e75b0c084')
const uriFactory = DynWinRtType.registerInterface('IUriRuntimeClassFactoryStructProgressTest', uriFactoryIid).addMethod(
'CreateUri',
new DynWinRtMethodSig().addIn(DynWinRtType.hstring()).addOut(DynWinRtType.object()),
)

const activationFactoryIid = WinGuid.parse('00000035-0000-0000-c000-000000000046')
const activationFactory = DynWinRtType.registerInterface(
'IActivationFactoryStructProgressTest',
activationFactoryIid,
).addMethod('ActivateInstance', new DynWinRtMethodSig().addOut(DynWinRtType.object()))

const progressStage = DynWinRtType.enumType('Windows.Web.Http.HttpProgressStage')
const referenceU64 = DynWinRtType.parameterized(WinGuid.parse('61c17706-2d65-11e0-9ae8-d48564015472'), [
DynWinRtType.u64(),
])
const httpProgress = DynWinRtType.structType('Windows.Web.Http.HttpProgress', [
progressStage,
DynWinRtType.u64(),
referenceU64,
DynWinRtType.u64(),
referenceU64,
DynWinRtType.u32(),
])
const reference = DynWinRtType.registerInterface('IReference_UInt64_StructProgressTest', referenceU64.iid()).addMethod(
'get_Value',
new DynWinRtMethodSig().addOut(DynWinRtType.u64()),
)

const clientIid = WinGuid.parse('7fda1151-3574-4880-a8ba-e6b1e0061f3d')
const clientType = DynWinRtType.registerInterface('IHttpClientStructProgressTest', clientIid)
for (const name of ['DeleteAsync', 'GetAsync', 'GetWithOptionAsync', 'GetBufferAsync', 'GetInputStreamAsync']) {
clientType.addMethod(name, new DynWinRtMethodSig())
}
clientType.addMethod(
'GetStringAsync',
new DynWinRtMethodSig()
.addIn(DynWinRtType.object())
.addOut(DynWinRtType.iAsyncOperationWithProgress(DynWinRtType.hstring(), httpProgress)),
)

const payload = 'dynwinrt-struct-progress-'.repeat(16_384)
const server = createServer((_request, response) => {
response.writeHead(200, {
'Content-Length': Buffer.byteLength(payload),
'Content-Type': 'text/plain; charset=utf-8',
Connection: 'close',
})
let offset = 0
const writeNext = () => {
if (offset >= payload.length) {
response.end()
return
}
const end = Math.min(offset + 8_192, payload.length)
response.write(payload.slice(offset, end))
offset = end
setTimeout(writeNext, 5)
}
writeNext()
})

await new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(0, '127.0.0.1', resolve)
})

try {
const address = server.address()
assert.ok(address && typeof address !== 'string')
const uri = uriFactory
.method(6)
.invoke(DynWinRtValue.activationFactory('Windows.Foundation.Uri').cast(uriFactoryIid), [
DynWinRtValue.hstring(`http://127.0.0.1:${address.port}/progress`),
])
const client = activationFactory
.method(6)
.invoke(DynWinRtValue.activationFactory('Windows.Web.Http.HttpClient').cast(activationFactoryIid), [])
const operation = clientType.method(11).invoke(client.cast(clientIid), [uri])
const snapshots = []

operation.onProgress((value) => {
const progress = value.asStruct()
const totalValue = progress.getObject(4)
const totalBytesToReceive = totalValue.isNull() ? null : reference.method(6).invoke(totalValue, []).toU64Bigint()
snapshots.push({
stage: progress.getI32(0),
bytesReceived: progress.getU64(3),
totalBytesToReceive,
retries: progress.getU32(5),
})
})

const result = await operation.toPromise()
await new Promise((resolve) => setImmediate(resolve))

assert.equal(result.toString(), payload)
assert.ok(
snapshots.some(
(progress) => progress.bytesReceived > 0n && progress.totalBytesToReceive === BigInt(Buffer.byteLength(payload)),
),
`expected retained receive totals, got ${JSON.stringify(
snapshots.map((progress) => ({
...progress,
bytesReceived: progress.bytesReceived.toString(),
totalBytesToReceive: progress.totalBytesToReceive?.toString() ?? null,
})),
)}`,
)
assert.ok(snapshots.every((progress) => typeof progress.stage === 'number' && typeof progress.retries === 'number'))
console.log('struct-progress-ok')
} finally {
await new Promise((resolve) => server.close(resolve))
}
73 changes: 71 additions & 2 deletions bindings/js/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,44 @@ mod tsfn_test_hooks;
static TABLE: std::sync::LazyLock<Arc<dynwinrt::MetadataTable>> =
std::sync::LazyLock::new(|| dynwinrt::MetadataTable::new());

fn ensure_progress_type_supported(progress_type: &dynwinrt::TypeHandle) -> napi::Result<()> {
match progress_type.kind() {
dynwinrt::TypeKind::Guid
| dynwinrt::TypeKind::ArrayOfIUnknown
| dynwinrt::TypeKind::Generic { .. }
| dynwinrt::TypeKind::OutValue(_)
| dynwinrt::TypeKind::Array(_) => Err(napi::Error::from_reason(format!(
"onProgress: progress callbacks do not support {:?} values",
progress_type.kind()
))),
dynwinrt::TypeKind::Bool
| dynwinrt::TypeKind::I8
| dynwinrt::TypeKind::U8
| dynwinrt::TypeKind::I16
| dynwinrt::TypeKind::U16
| dynwinrt::TypeKind::Char16
| dynwinrt::TypeKind::I32
| dynwinrt::TypeKind::U32
| dynwinrt::TypeKind::I64
| dynwinrt::TypeKind::U64
| dynwinrt::TypeKind::F32
| dynwinrt::TypeKind::F64
| dynwinrt::TypeKind::HString
| dynwinrt::TypeKind::Object
| dynwinrt::TypeKind::HResult
| dynwinrt::TypeKind::Interface(_)
| dynwinrt::TypeKind::Delegate(_)
| dynwinrt::TypeKind::IAsyncAction
| dynwinrt::TypeKind::IAsyncActionWithProgress(_)
| dynwinrt::TypeKind::IAsyncOperation(_)
| dynwinrt::TypeKind::IAsyncOperationWithProgress(_)
| dynwinrt::TypeKind::RuntimeClass(_)
| dynwinrt::TypeKind::Parameterized(_)
| dynwinrt::TypeKind::Enum(_)
| dynwinrt::TypeKind::Struct(_) => Ok(()),
}
}

// ======================================================================
// Runtime initialization
// ======================================================================
Expand Down Expand Up @@ -1319,6 +1357,7 @@ impl DynWinRTValue {
let progress_type = async_info
.progress_type()
.ok_or_else(|| napi::Error::from_reason("onProgress: not a WithProgress async type"))?;
ensure_progress_type_supported(&progress_type)?;

let handler_iid = async_info
.progress_handler_iid()
Expand Down Expand Up @@ -1353,7 +1392,13 @@ impl DynWinRTValue {
}
});
let handler =
dynwinrt::create_progress_handler_with_result(handler_iid, progress_type, progress_cb);
dynwinrt::try_create_progress_handler_with_result(handler_iid, progress_type, progress_cb)
.map_err(|error| {
napi::Error::from_reason(format!(
"onProgress: failed to create progress handler: {}",
error.message()
))
})?;

async_info
.set_progress_handler(&handler)
Expand Down Expand Up @@ -1914,6 +1959,26 @@ mod js_boundary_tests {
[0x80004005u32 as i32],
);
}

#[test]
fn progress_type_validation_allows_structs_and_rejects_unsupported_shapes() {
let progress = TABLE.struct_type("Test.JsStructProgress", &[TABLE.u64_type()]);
assert!(ensure_progress_type_supported(&progress).is_ok());

let value_type = TABLE.u32_type();
for unsupported in [
TABLE.guid_type(),
TABLE.array_of_iunknown(),
TABLE.generic(
windows::core::GUID::from_u128(0x11111111_2222_3333_4444_555555555555),
1,
),
TABLE.out_value(&value_type),
TABLE.array(&value_type),
] {
assert!(ensure_progress_type_supported(&unsupported).is_err());
}
}
}

// ======================================================================
Expand Down Expand Up @@ -2759,7 +2824,11 @@ impl DynWinRtDelegate {
}
});

let value = dynwinrt::delegate::create_delegate_value(iid.0, type_handles, delegate_callback);
let value =
dynwinrt::delegate::try_create_delegate_value(iid.0, type_handles, delegate_callback)
.map_err(|error| {
napi::Error::from_reason(format!("DynWinRtDelegate.create: {}", error.message()))
})?;
Ok(DynWinRtDelegate(value))
}

Expand Down
58 changes: 54 additions & 4 deletions bindings/py/src/async_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,35 @@ pub(crate) fn ensure_progress_type_supported(progress_type: &dynwinrt::TypeHandl
| dynwinrt::TypeKind::ArrayOfIUnknown
| dynwinrt::TypeKind::Generic { .. }
| dynwinrt::TypeKind::OutValue(_)
| dynwinrt::TypeKind::Struct(_)
| dynwinrt::TypeKind::Array(_) => Err(PyRuntimeError::new_err(format!(
"progress callbacks do not yet support {:?} values",
"progress callbacks do not support {:?} values",
progress_type.kind()
))),
_ => Ok(()),
dynwinrt::TypeKind::Bool
| dynwinrt::TypeKind::I8
| dynwinrt::TypeKind::U8
| dynwinrt::TypeKind::I16
| dynwinrt::TypeKind::U16
| dynwinrt::TypeKind::Char16
| dynwinrt::TypeKind::I32
| dynwinrt::TypeKind::U32
| dynwinrt::TypeKind::I64
| dynwinrt::TypeKind::U64
| dynwinrt::TypeKind::F32
| dynwinrt::TypeKind::F64
| dynwinrt::TypeKind::HString
| dynwinrt::TypeKind::Object
| dynwinrt::TypeKind::HResult
| dynwinrt::TypeKind::Interface(_)
| dynwinrt::TypeKind::Delegate(_)
| dynwinrt::TypeKind::IAsyncAction
| dynwinrt::TypeKind::IAsyncActionWithProgress(_)
| dynwinrt::TypeKind::IAsyncOperation(_)
| dynwinrt::TypeKind::IAsyncOperationWithProgress(_)
| dynwinrt::TypeKind::RuntimeClass(_)
| dynwinrt::TypeKind::Parameterized(_)
| dynwinrt::TypeKind::Enum(_)
| dynwinrt::TypeKind::Struct(_) => Ok(()),
}
}

Expand Down Expand Up @@ -421,7 +444,13 @@ impl DynWinRTAsyncWithProgress {
});
});
let handler =
dynwinrt::create_progress_handler(handler_iid, progress_type, progress_callback);
dynwinrt::try_create_progress_handler(handler_iid, progress_type, progress_callback)
.map_err(|error| {
map_dynwinrt_error_with_context(
error,
"failed to create WinRT progress handler",
)
})?;
finish_progress_registration(info.set_progress_handler(&handler), || {
info.is_started().map_err(map_dynwinrt_error)
})
Expand Down Expand Up @@ -476,4 +505,25 @@ mod tests {
let result = finish_progress_registration(Err(set_progress_error()), || Ok(true));
assert!(result.is_err());
}

#[test]
fn progress_type_validation_allows_structs_and_rejects_unsupported_shapes() {
let table = dynwinrt::MetadataTable::new();
let progress = table.struct_type("Test.PythonStructProgress", &[table.u64_type()]);
assert!(ensure_progress_type_supported(&progress).is_ok());

let value_type = table.u32_type();
for unsupported in [
table.guid_type(),
table.array_of_iunknown(),
table.generic(
windows::core::GUID::from_u128(0xaaaaaaaa_bbbb_cccc_dddd_eeeeeeeeeeee),
1,
),
table.out_value(&value_type),
table.array(&value_type),
] {
assert!(ensure_progress_type_supported(&unsupported).is_err());
}
}
}
Loading
Loading