Compare commits
176 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e13152f340 | |||
| deba5ed115 | |||
| 4bf71a0b2c | |||
| b4a7bac4c0 | |||
| 6df373ae4c | |||
| fe44e3c18a | |||
| 523f944f3e | |||
| c33f1e6047 | |||
| 92cc4688e6 | |||
| a155554038 | |||
| 68f905a344 | |||
| 5abc222c72 | |||
| da3aa7b0b2 | |||
| f0ec068430 | |||
| 1a1d14a9fd | |||
| b2448510ac | |||
| 75610e3f55 | |||
| 5032166106 | |||
| 76a042d663 | |||
| 4a19854eb9 | |||
| a4467e23ef | |||
| eacfeff9fb | |||
| b4bc2df015 | |||
| fd2a0ac4c7 | |||
| 555e4be51f | |||
| 1d8c0d83c4 | |||
| 6600f2a7bd | |||
| 803a207ad2 | |||
| 97e583e96b | |||
| eaf479349d | |||
| 83a4d41fce | |||
| 0d6193cdc4 | |||
| 8cd3e1c20e | |||
| 5c28458624 | |||
| 0b389f5a97 | |||
| 108c4bb118 | |||
| cf54a278e1 | |||
| 81b2aacfe2 | |||
| 5932fe2fd3 | |||
| 310dfab8b4 | |||
| ba157b4b4f | |||
| 87e22dd529 | |||
| d9eaf4b056 | |||
| 2c5c5e5c7e | |||
| b3ebf583ad | |||
| edb812d859 | |||
| 795eee72e3 | |||
| 615b487a77 | |||
| 382861c602 | |||
| ba2b936609 | |||
| 7fc1955287 | |||
| 54480dde61 | |||
| 581b541801 | |||
| d3cb311aae | |||
| 186d03e5cc | |||
| 6bae5ea3a3 | |||
| 430187c28b | |||
| f5b50c4484 | |||
| 4a0f88b17d | |||
| 82996aa8e6 | |||
| 712cb06442 | |||
| 4d77279e7e | |||
| 6079c62709 | |||
| 37ef27e8ed | |||
| db2218f395 | |||
| bc28fee641 | |||
| 15fceed536 | |||
| afa82e0989 | |||
| b9ef09d26e | |||
| 7d66967122 | |||
| 2f8404d2ef | |||
| 2b92be02b9 | |||
| 056f0d8808 | |||
| 42b0037376 | |||
| de7639a3e9 | |||
| 8738735f0d | |||
| e80f3c70b6 | |||
| 24cc5fd0f0 | |||
| c5153d68bb | |||
| 0e56b5befb | |||
| c5e7479ee4 | |||
| 8a0c59d7e8 | |||
| 828e3e6cf6 | |||
| 7de4efeb02 | |||
| 6f0d142639 | |||
| 11cc6715ed | |||
| f90bff01db | |||
| 6add4b4acc | |||
| 325106920f | |||
| 8aaab82287 | |||
| b3ae200b11 | |||
| 71d2c39f01 | |||
| a68f0cf222 | |||
| 83eba4bec5 | |||
| 10bd0c0e4d | |||
| 865c22a884 | |||
| d48099f0d0 | |||
| bd1d1f1c0e | |||
| 327e9c5f94 | |||
| d2d2e5f68f | |||
| d692232191 | |||
| 65943597d4 | |||
| 27ed65114e | |||
| 397d3c5c4f | |||
| dc9c0c950c | |||
| 867bf18116 | |||
| a4ed605f74 | |||
| 4e02927f01 | |||
| 47b1fd422c | |||
| 9b21ca3554 | |||
| 01f5e6ad91 | |||
| 82eb0ad569 | |||
| f711a55be4 | |||
| f490ae2593 | |||
| 39f9fd8946 | |||
| bb7be14d1d | |||
| 8ac6642bf8 | |||
| 4e8928cf71 | |||
| f4423dfb6d | |||
| 3ff4969224 | |||
| 12881ca791 | |||
| 6e356da092 | |||
| a739fadb5f | |||
| 6b3c117d1e | |||
| c7d5b83390 | |||
| 1ac5bcafb2 | |||
| e7c2c546b5 | |||
| a14098468b | |||
| e030661c1b | |||
| 4e933802a7 | |||
| 6c3edf4516 | |||
| 9de2c0c43d | |||
| bc61598b44 | |||
| 335c952f00 | |||
| 3256733d24 | |||
| 4f0f03fca5 | |||
| 9ca200f814 | |||
| fe19c478c0 | |||
| d0bc78cd43 | |||
| 730fdc93e0 | |||
| 55470e3e09 | |||
| b4016e738c | |||
| 10004879f6 | |||
| 168bb9a39a | |||
| a7edc8f8bf | |||
| 0765eb4de3 | |||
| 26d0e2c471 | |||
| 65d83b1400 | |||
| 7b621e3f64 | |||
| 0f88a953d7 | |||
| ddad573b75 | |||
| 8d3352f2c6 | |||
| eed1e88a37 | |||
| 4731ab535c | |||
| 51a9dadf62 | |||
| 133c83029b | |||
| 047d875fe6 | |||
| b0041c5d18 | |||
| 907aa49aea | |||
| 4fc355b357 | |||
| bd4a09a35e | |||
| d431ff9660 | |||
| 3d11ac3316 | |||
| daff16cfd2 | |||
| 6ce61a4f77 | |||
| 4ea2c4fd86 | |||
| 09e01de9c8 | |||
| 41a2d70f8f | |||
| 79f73e04fd | |||
| f2118f7028 | |||
| 9159f6f093 | |||
| d6939432f9 | |||
| 02143ef7e2 | |||
| c032852065 | |||
| 1d93e77234 | |||
| 0a670eb381 |
@@ -45,6 +45,7 @@ build/
|
|||||||
out/
|
out/
|
||||||
tmp/
|
tmp/
|
||||||
temp/
|
temp/
|
||||||
|
install/
|
||||||
|
|
||||||
# .NET
|
# .NET
|
||||||
**/bin/
|
**/bin/
|
||||||
|
|||||||
@@ -1,481 +0,0 @@
|
|||||||
# MXAccess Gateway Agent Guide
|
|
||||||
|
|
||||||
Repository: https://gitea.dohertylan.com/dohertj2/mxaccessgw
|
|
||||||
|
|
||||||
This project builds a gateway that gives modern clients full MXAccess parity
|
|
||||||
without requiring those clients to load MXAccess COM, run as x86, or own an STA
|
|
||||||
message pump. Treat the installed MXAccess COM component as the compatibility
|
|
||||||
baseline.
|
|
||||||
|
|
||||||
Toolchain paths, versions, and external analysis locations are recorded in
|
|
||||||
`docs/toolchain-links.md`. Use that file before searching for compilers,
|
|
||||||
runtimes, protobuf tools, MXAccess notes, or Galaxy Repository SQL notes.
|
|
||||||
|
|
||||||
Implementation planning is recorded in `docs/implementation-plan-index.md`.
|
|
||||||
Follow the order there unless the user explicitly reprioritizes: gateway first,
|
|
||||||
MXAccess worker instance second, clients third.
|
|
||||||
|
|
||||||
## Core Contract
|
|
||||||
|
|
||||||
Preserve MXAccess behavior first:
|
|
||||||
|
|
||||||
- public MXAccess command semantics,
|
|
||||||
- native MXAccess event families,
|
|
||||||
- STA/message-pump delivery behavior,
|
|
||||||
- installed-provider quirks,
|
|
||||||
- HRESULT/status/value marshaling,
|
|
||||||
- per-client isolation.
|
|
||||||
|
|
||||||
Do not simplify, normalize, or "fix" MXAccess behavior unless an explicit
|
|
||||||
non-parity mode is being implemented and tested. `MxAsbClient` and managed NMX
|
|
||||||
are future acceleration paths only; they do not define the parity contract.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
The intended split is:
|
|
||||||
|
|
||||||
```text
|
|
||||||
client
|
|
||||||
-> gRPC over TCP
|
|
||||||
-> .NET 10 x64 gateway
|
|
||||||
-> session manager
|
|
||||||
-> per-session .NET Framework 4.8 x86 worker process
|
|
||||||
-> dedicated STA thread
|
|
||||||
-> MXAccess COM instance
|
|
||||||
-> Windows/COM message pump
|
|
||||||
-> command queue
|
|
||||||
-> event sink
|
|
||||||
```
|
|
||||||
|
|
||||||
The gateway must never instantiate or call MXAccess directly. All MXAccess COM
|
|
||||||
interaction belongs in the worker process on its dedicated STA thread.
|
|
||||||
|
|
||||||
The worker must not host public gRPC. Gateway-to-worker communication should use
|
|
||||||
a small local IPC protocol, with named pipes and protobuf-framed messages as the
|
|
||||||
default design.
|
|
||||||
|
|
||||||
## Runtime Targets
|
|
||||||
|
|
||||||
- Gateway: .NET 10, C#, x64 preferred, ASP.NET Core gRPC.
|
|
||||||
- Worker: .NET Framework 4.8, C#, x86 by default.
|
|
||||||
- Worker IPC: one bidirectional named pipe per worker.
|
|
||||||
- Worker process model: one external client session maps to one worker by
|
|
||||||
default.
|
|
||||||
|
|
||||||
## Style Guides
|
|
||||||
|
|
||||||
Follow the project documentation guide and the language guide for every changed
|
|
||||||
area:
|
|
||||||
|
|
||||||
| Area | Style guide |
|
|
||||||
|------|-------------|
|
|
||||||
| Documentation | `StyleGuide.md` |
|
|
||||||
| Gateway, worker, .NET client, and C# tests | `docs/style-guides/CSharpStyleGuide.md` |
|
|
||||||
| Public gRPC and worker IPC contracts | `docs/style-guides/ProtobufStyleGuide.md` |
|
|
||||||
| Go client | `docs/style-guides/GoStyleGuide.md` |
|
|
||||||
| Rust client | `docs/style-guides/RustStyleGuide.md` |
|
|
||||||
| Python client | `docs/style-guides/PythonStyleGuide.md` |
|
|
||||||
| Java client | `docs/style-guides/JavaStyleGuide.md` |
|
|
||||||
|
|
||||||
When a change crosses languages, apply every affected style guide. Generated
|
|
||||||
code follows its generator output; do not hand-edit it to match handwritten
|
|
||||||
style.
|
|
||||||
|
|
||||||
## Expected Layout
|
|
||||||
|
|
||||||
Prefer this structure unless there is a strong reason to adjust it:
|
|
||||||
|
|
||||||
```text
|
|
||||||
src/MxGateway.Contracts/
|
|
||||||
Protos/
|
|
||||||
mxaccess_gateway.proto
|
|
||||||
mxaccess_worker.proto
|
|
||||||
Generated/
|
|
||||||
|
|
||||||
src/MxGateway.Server/
|
|
||||||
Program.cs
|
|
||||||
Sessions/
|
|
||||||
Workers/
|
|
||||||
Grpc/
|
|
||||||
Dashboard/
|
|
||||||
Metrics/
|
|
||||||
|
|
||||||
src/MxGateway.Worker/
|
|
||||||
Program.cs
|
|
||||||
Ipc/
|
|
||||||
Sta/
|
|
||||||
MxAccess/
|
|
||||||
Conversion/
|
|
||||||
|
|
||||||
src/MxGateway.Tests/
|
|
||||||
contract tests
|
|
||||||
gateway session tests
|
|
||||||
fake worker tests
|
|
||||||
|
|
||||||
src/MxGateway.Worker.Tests/
|
|
||||||
value/status conversion tests
|
|
||||||
STA queue tests
|
|
||||||
|
|
||||||
src/MxGateway.IntegrationTests/
|
|
||||||
optional live MXAccess tests
|
|
||||||
|
|
||||||
clients/dotnet/
|
|
||||||
.NET 10 C# client library, test CLI, and tests
|
|
||||||
|
|
||||||
clients/go/
|
|
||||||
Go client module, test CLI, and tests
|
|
||||||
|
|
||||||
clients/rust/
|
|
||||||
Rust client crate, test CLI, and tests
|
|
||||||
|
|
||||||
clients/python/
|
|
||||||
Python client package, test CLI, and tests
|
|
||||||
|
|
||||||
clients/java/
|
|
||||||
Java client library, test CLI, and tests
|
|
||||||
```
|
|
||||||
|
|
||||||
The contracts project may multi-target, or the `.proto` files may be shared as
|
|
||||||
source inputs to both gateway and worker builds.
|
|
||||||
|
|
||||||
## Public API Shape
|
|
||||||
|
|
||||||
The external API should be session-oriented. Initial rollout should prefer
|
|
||||||
unary `OpenSession`, `CloseSession`, and `Invoke`, plus server-streaming
|
|
||||||
`StreamEvents`. Add a bidirectional `Session` stream after the command and event
|
|
||||||
model is stable.
|
|
||||||
|
|
||||||
Do not compress MXAccess into generic verbs too early. Use a command enum with
|
|
||||||
method-specific payloads so parity can be tested method by method.
|
|
||||||
|
|
||||||
Core MXAccess commands to represent:
|
|
||||||
|
|
||||||
- `Register`
|
|
||||||
- `Unregister`
|
|
||||||
- `AddItem`
|
|
||||||
- `AddItem2`
|
|
||||||
- `RemoveItem`
|
|
||||||
- `Advise`
|
|
||||||
- `UnAdvise`
|
|
||||||
- `AdviseSupervisory`
|
|
||||||
- `AddBufferedItem`
|
|
||||||
- `SetBufferedUpdateInterval`
|
|
||||||
- `Suspend`
|
|
||||||
- `Activate`
|
|
||||||
- `Write`
|
|
||||||
- `Write2`
|
|
||||||
- `WriteSecured`
|
|
||||||
- `WriteSecured2`
|
|
||||||
- `AuthenticateUser`
|
|
||||||
- `ArchestrAUserToId`
|
|
||||||
|
|
||||||
Diagnostics may include `Ping`, `GetSessionState`, `GetWorkerInfo`,
|
|
||||||
`DrainEvents`, and `ShutdownWorker`.
|
|
||||||
|
|
||||||
## Event Requirements
|
|
||||||
|
|
||||||
Represent every public MXAccess event family:
|
|
||||||
|
|
||||||
- `OnDataChange`
|
|
||||||
- `OnWriteComplete`
|
|
||||||
- `OperationComplete`
|
|
||||||
- `OnBufferedDataChange`
|
|
||||||
|
|
||||||
Preserve per-worker event order. The gateway must not reorder events emitted by
|
|
||||||
the same MXAccess instance.
|
|
||||||
|
|
||||||
Event DTOs should carry event family, session id, server handle, item handle,
|
|
||||||
value, quality, timestamp, `MXSTATUS_PROXY[]` equivalent, raw HRESULT/status
|
|
||||||
fields when available, event sequence, worker timestamp, and gateway receive
|
|
||||||
timestamp.
|
|
||||||
|
|
||||||
## Value And Status Rules
|
|
||||||
|
|
||||||
Use a protobuf value union that can represent COM `VARIANT` values and arrays.
|
|
||||||
When a value cannot be losslessly converted, preserve both the best typed
|
|
||||||
projection and enough raw diagnostic metadata to reproduce the case.
|
|
||||||
|
|
||||||
Represent `MXSTATUS_PROXY` explicitly. Do not collapse status arrays into a
|
|
||||||
single success flag.
|
|
||||||
|
|
||||||
Command replies should include protocol status, COM HRESULT if available,
|
|
||||||
MXAccess return values, method-specific out parameters, and status arrays where
|
|
||||||
the MXAccess method emits them.
|
|
||||||
|
|
||||||
## Galaxy Repository SQL Discovery
|
|
||||||
|
|
||||||
Galaxy tags, hierarchy, and attribute details can be queried from the AVEVA /
|
|
||||||
Wonderware System Platform Galaxy Repository SQL Server database. Use this as a
|
|
||||||
discovery and metadata path only; runtime MXAccess parity still belongs to the
|
|
||||||
MXAccess-backed worker unless an explicit non-parity backend is being designed.
|
|
||||||
|
|
||||||
Full notes, schema details, screenshots, and query examples are in:
|
|
||||||
|
|
||||||
```text
|
|
||||||
C:\Users\dohertj2\Desktop\lmxopcua\gr
|
|
||||||
```
|
|
||||||
|
|
||||||
Important files in that notes directory:
|
|
||||||
|
|
||||||
- `connectioninfo.md` - SQL Server connection details and `sqlcmd` usage.
|
|
||||||
- `layout.md` - hierarchy vs `tag_name` relationship.
|
|
||||||
- `build_layout_plan.md` - extraction plan for hierarchy and attributes.
|
|
||||||
- `schema.md` and `ddl/` - Galaxy Repository schema reference.
|
|
||||||
- `queries/hierarchy.sql` - deployed object hierarchy.
|
|
||||||
- `queries/attributes.sql` - user-defined dynamic attributes.
|
|
||||||
- `queries/attributes_extended.sql` - system plus user-defined attributes.
|
|
||||||
- `queries/change_detection.sql` - deployment-change polling via
|
|
||||||
`galaxy.time_of_last_deploy`.
|
|
||||||
|
|
||||||
Current documented connection is SQL Server `localhost`, database `ZB`, Windows
|
|
||||||
Auth. Example:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
sqlcmd -S localhost -d ZB -E -Q "SELECT time_of_last_deploy FROM galaxy;"
|
|
||||||
```
|
|
||||||
|
|
||||||
Key tables from the notes are `gobject`, `template_definition`,
|
|
||||||
`dynamic_attribute`, `attribute_definition`, `primitive_instance`, and
|
|
||||||
`galaxy`. The hierarchy uses contained names for human-readable browsing, while
|
|
||||||
runtime tag references use globally unique `tag_name` values such as
|
|
||||||
`<tag_name>.<AttributeName>`.
|
|
||||||
|
|
||||||
## MXAccess Analysis Source
|
|
||||||
|
|
||||||
Use the local MXAccess analysis project when answering questions about installed
|
|
||||||
MXAccess classes, interfaces, fields, events, HRESULT/status behavior, value
|
|
||||||
projection, captures, and parity gaps:
|
|
||||||
|
|
||||||
```text
|
|
||||||
C:\Users\dohertj2\Desktop\mxaccess
|
|
||||||
```
|
|
||||||
|
|
||||||
Primary files:
|
|
||||||
|
|
||||||
- `README.md` - overview of available analysis and capture artifacts.
|
|
||||||
- `docs/MXAccess-Public-API.md` - COM class, ProgID, CLSID, method list,
|
|
||||||
event signatures, `MxDataType`, `MxStatus`, and `MXSTATUS_PROXY`.
|
|
||||||
- `docs/MXAccess-Reverse-Engineering.md` - installed runtime path and x86 COM
|
|
||||||
constraints.
|
|
||||||
- `docs/Current-Sprint-State.md` and `docs/DotNet10-Native-Library-Plan.md` -
|
|
||||||
current parity gaps and managed native-client research status.
|
|
||||||
- `src/MxTraceHarness/` - x86 MXAccess harness examples using the real COM
|
|
||||||
interop assembly.
|
|
||||||
- `captures/` and `analysis/` - observed native behavior and generated
|
|
||||||
reverse-engineering artifacts.
|
|
||||||
|
|
||||||
Concrete MXAccess COM target from the analysis:
|
|
||||||
|
|
||||||
- class: `ArchestrA.MxAccess.LMXProxyServerClass`
|
|
||||||
- CLSID: `{C30B52F5-2CB5-4760-AF0A-3A344A7EB5DC}`
|
|
||||||
- ProgID: `LMXProxy.LMXProxyServer.1`
|
|
||||||
- version-independent ProgID: `LMXProxy.LMXProxyServer`
|
|
||||||
- registered server: `C:\Program Files (x86)\ArchestrA\Framework\Bin\LmxProxy.dll`
|
|
||||||
- interop assembly:
|
|
||||||
`C:\Program Files (x86)\ArchestrA\Framework\Bin\ArchestrA.MXAccess.dll`
|
|
||||||
- threading model: `Apartment`
|
|
||||||
|
|
||||||
## Worker Rules
|
|
||||||
|
|
||||||
Each worker owns:
|
|
||||||
|
|
||||||
- one process,
|
|
||||||
- one MXAccess session,
|
|
||||||
- one dedicated STA thread,
|
|
||||||
- one MXAccess COM object,
|
|
||||||
- one inbound command queue,
|
|
||||||
- one outbound event queue.
|
|
||||||
|
|
||||||
All MXAccess operations must run on the STA. A plain blocking queue is not
|
|
||||||
enough for the STA; the STA loop must pump Windows/COM messages and service
|
|
||||||
queued commands.
|
|
||||||
|
|
||||||
Do not block the STA on pipe writes, gRPC calls, or slow consumers. Event
|
|
||||||
handlers should convert event args, enqueue outbound events, and return to
|
|
||||||
pumping messages.
|
|
||||||
|
|
||||||
On graceful shutdown, reject new commands, optionally clean up active MXAccess
|
|
||||||
handles, detach events, release the COM object, uninitialize COM, and exit. If
|
|
||||||
graceful shutdown exceeds the configured timeout, the gateway may kill the
|
|
||||||
worker.
|
|
||||||
|
|
||||||
## IPC Rules
|
|
||||||
|
|
||||||
Default pipe name shape:
|
|
||||||
|
|
||||||
```text
|
|
||||||
mxaccess-gateway-{gatewayProcessId}-{sessionId}
|
|
||||||
```
|
|
||||||
|
|
||||||
Frame messages as:
|
|
||||||
|
|
||||||
```text
|
|
||||||
uint32 little-endian payload_length
|
|
||||||
payload_length bytes protobuf WorkerEnvelope
|
|
||||||
```
|
|
||||||
|
|
||||||
Every envelope should include protocol version, session id, monotonic sender
|
|
||||||
sequence, correlation id, and a typed body. Protocol version mismatch should
|
|
||||||
fail session creation.
|
|
||||||
|
|
||||||
Pipe security should be local-machine only, with ACLs restricted to the gateway
|
|
||||||
identity and launched worker identity. Prefer a per-session nonce handshake.
|
|
||||||
|
|
||||||
## Gateway Rules
|
|
||||||
|
|
||||||
The gateway is responsible for:
|
|
||||||
|
|
||||||
- public TCP/gRPC API,
|
|
||||||
- Blazor Server dashboard using Bootstrap CSS/JS only,
|
|
||||||
- authn/authz when needed,
|
|
||||||
- session creation and teardown,
|
|
||||||
- worker launch and lifecycle management,
|
|
||||||
- command routing,
|
|
||||||
- event streaming,
|
|
||||||
- leases, heartbeats, timeouts, and quotas,
|
|
||||||
- worker kill/restart policy,
|
|
||||||
- metrics and structured logs.
|
|
||||||
|
|
||||||
The gRPC layer should stay thin: validate request, find session, call the
|
|
||||||
session worker client, map worker replies to public replies, and stream events.
|
|
||||||
Keep MXAccess-specific translation logic testable outside the gRPC handlers.
|
|
||||||
|
|
||||||
Dashboard code should also stay thin and read-only for v1. Use a snapshot
|
|
||||||
service over session/worker/metrics state; do not let Razor components mutate
|
|
||||||
gateway sessions or workers directly. Do not use MudBlazor or other Blazor UI
|
|
||||||
component libraries.
|
|
||||||
|
|
||||||
Gateway restart should not try to reattach old workers in the first version.
|
|
||||||
Terminate orphaned workers on startup if that behavior is implemented.
|
|
||||||
|
|
||||||
## Command, Timeout, And Cancellation Semantics
|
|
||||||
|
|
||||||
Command lifecycle:
|
|
||||||
|
|
||||||
```text
|
|
||||||
client gRPC command
|
|
||||||
gateway validates session and payload
|
|
||||||
gateway assigns correlation id
|
|
||||||
gateway writes WorkerCommand to pipe
|
|
||||||
worker queues command to STA
|
|
||||||
STA executes MXAccess method
|
|
||||||
worker captures return/out/status/HRESULT
|
|
||||||
worker sends WorkerCommandReply
|
|
||||||
gateway completes gRPC response
|
|
||||||
```
|
|
||||||
|
|
||||||
Canceling a gRPC call should stop waiting in the gateway, but it cannot safely
|
|
||||||
abort an in-flight COM call on the STA. Hard cancellation means killing the
|
|
||||||
worker process.
|
|
||||||
|
|
||||||
If a command wedges the STA beyond a configured grace period, the gateway should
|
|
||||||
kill the worker and fail the session.
|
|
||||||
|
|
||||||
## Backpressure Policy
|
|
||||||
|
|
||||||
Worker outbound events must use a bounded queue. For parity testing, prefer
|
|
||||||
fail-fast behavior over silent drops. Production coalescing or drop policies
|
|
||||||
must be explicit and observable.
|
|
||||||
|
|
||||||
The gateway should preserve per-session event order, apply backpressure from
|
|
||||||
slow gRPC streams, and disconnect or coalesce only according to an explicit
|
|
||||||
policy.
|
|
||||||
|
|
||||||
## Security And Logging
|
|
||||||
|
|
||||||
Use TLS for remote gRPC when crossing machine boundaries. Authentication may be
|
|
||||||
Windows auth, mTLS, or a deployment-specific token.
|
|
||||||
|
|
||||||
Commands that write, authenticate users, or alter runtime state need explicit
|
|
||||||
authorization design.
|
|
||||||
|
|
||||||
Never log passwords or raw credential values for `AuthenticateUser`,
|
|
||||||
`WriteSecured`, or related secured operations. Do not log full values by
|
|
||||||
default; make value logging opt-in and redacted.
|
|
||||||
|
|
||||||
## Testing Expectations
|
|
||||||
|
|
||||||
Use focused tests for:
|
|
||||||
|
|
||||||
- contract/protobuf compatibility,
|
|
||||||
- gateway session state and worker lifecycle,
|
|
||||||
- gateway behavior with a fake worker,
|
|
||||||
- worker value/status conversion,
|
|
||||||
- STA queue and message-pump behavior.
|
|
||||||
|
|
||||||
Live MXAccess integration tests are optional but should be isolated because they
|
|
||||||
depend on installed COM components and provider behavior.
|
|
||||||
|
|
||||||
Parity tests should compare direct MXAccess behavior against the gateway:
|
|
||||||
|
|
||||||
- return values,
|
|
||||||
- HRESULTs and exceptions,
|
|
||||||
- event sequence,
|
|
||||||
- value projection,
|
|
||||||
- quality/status arrays,
|
|
||||||
- invalid handle behavior,
|
|
||||||
- cross-server handle behavior,
|
|
||||||
- cleanup behavior.
|
|
||||||
|
|
||||||
Known important parity areas:
|
|
||||||
|
|
||||||
- `WriteSecured` may fail before a value-bearing NMX body is emitted.
|
|
||||||
- `WriteSecured2` can succeed in observed native paths.
|
|
||||||
- `OperationComplete` is distinct from write completion.
|
|
||||||
- `OnBufferedDataChange` has a distinct public event shape.
|
|
||||||
- Invalid handles and cross-server handles have specific exception/status
|
|
||||||
behavior.
|
|
||||||
- STA message pumping is required for event delivery.
|
|
||||||
|
|
||||||
## Source Update Workflow
|
|
||||||
|
|
||||||
When source code changes, build the affected component before handing work
|
|
||||||
back. If the change crosses component boundaries, build each affected component
|
|
||||||
instead of relying on a single top-level build.
|
|
||||||
|
|
||||||
Use the native build and test command for each changed area:
|
|
||||||
|
|
||||||
| Changed area | Required verification |
|
|
||||||
|--------------|-----------------------|
|
|
||||||
| Contracts or `.proto` files | regenerate generated code, then build gateway, worker, and every generated client touched by the contract |
|
|
||||||
| Gateway server, sessions, workers, gRPC, dashboard, or metrics | build the .NET 10 gateway project and run affected gateway or fake-worker tests |
|
|
||||||
| Worker IPC, STA, MXAccess, or conversion code | build the .NET Framework 4.8 x86 worker project and run affected worker tests |
|
|
||||||
| Shared test infrastructure | run every test suite that consumes the changed helpers |
|
|
||||||
| .NET client | build the .NET client library, CLI, and tests |
|
|
||||||
| Go client | run Go formatting, build, and tests for the Go module |
|
|
||||||
| Rust client | run Rust formatting, build or check, and tests for the Rust crate |
|
|
||||||
| Python client | run Python formatting or linting if configured, package/build checks, and tests |
|
|
||||||
| Java client | build the Java client library, CLI, and tests |
|
|
||||||
| Integration tests | run them only when the required MXAccess COM component, provider state, and external services are available; otherwise document why they were skipped |
|
|
||||||
|
|
||||||
Update affected documentation in the same change as the source update. This
|
|
||||||
includes `gateway.md`, component design docs under `docs/`, client docs, API
|
|
||||||
contract notes, test instructions, and operational guidance. Documentation must
|
|
||||||
follow `StyleGuide.md`: write technical present-tense prose, explain the reason
|
|
||||||
for non-obvious choices, use exact code names, specify languages on code
|
|
||||||
blocks, use relative links for internal docs, and avoid stale temporary notes.
|
|
||||||
Source code and contract changes must also follow the relevant language guide
|
|
||||||
from the Style Guides section.
|
|
||||||
|
|
||||||
Do not leave documentation describing old behavior after changing public APIs,
|
|
||||||
contracts, configuration, build steps, security behavior, event shapes, value
|
|
||||||
conversion, status mapping, lifecycle rules, or client semantics.
|
|
||||||
|
|
||||||
## Implementation Priority
|
|
||||||
|
|
||||||
Build the smallest end-to-end slice first:
|
|
||||||
|
|
||||||
1. .NET 10 gateway starts.
|
|
||||||
2. Client calls `OpenSession`.
|
|
||||||
3. Gateway launches .NET Framework 4.8 x86 worker.
|
|
||||||
4. Worker creates STA and MXAccess COM object.
|
|
||||||
5. Client calls `Register`.
|
|
||||||
6. Client calls `AddItem`.
|
|
||||||
7. Client calls `Advise`.
|
|
||||||
8. Worker forwards one `OnDataChange` event to the gateway.
|
|
||||||
9. Gateway streams the event to the client.
|
|
||||||
10. Client calls `CloseSession`.
|
|
||||||
11. Gateway shuts down the worker.
|
|
||||||
|
|
||||||
That slice proves the high-risk requirements: process isolation, STA ownership,
|
|
||||||
message pumping, command routing, and event streaming.
|
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## Project Overview
|
||||||
|
|
||||||
|
`mxaccessgw` is the MXAccess Gateway: a gRPC service that gives modern (.NET, Go, Rust, Python, Java) clients full MXAccess parity without forcing them to load 32-bit MXAccess COM, run x86, or own an STA message pump.
|
||||||
|
|
||||||
|
The architecture is a two-process design — read `gateway.md` before making structural changes:
|
||||||
|
|
||||||
|
- **Gateway** (`src/MxGateway.Server`, .NET 10, x64): ASP.NET Core gRPC server. Owns the public API, sessions, auth, the Blazor dashboard, and the Galaxy Repository SQL browse RPCs. **Never instantiates MXAccess COM directly.**
|
||||||
|
- **Worker** (`src/MxGateway.Worker`, .NET Framework 4.8, **x86**): one process per session. Owns one MXAccess COM instance on a dedicated STA, pumps Windows messages, and converts COM events to protobuf.
|
||||||
|
- **IPC**: gateway↔worker uses one bidirectional named pipe per worker (`mxaccess-gateway-{gatewayPid}-{sessionId}`) with length-prefixed `WorkerEnvelope` protobuf frames. Gateway hosts the pipe server and launches the worker. **gRPC is not used inside the worker** — .NET Framework 4.8 doesn't have a first-class gRPC stack.
|
||||||
|
- **Contracts** (`src/MxGateway.Contracts`): multi-targets `net10.0;net48` and owns the `.proto` files (`mxaccess_gateway.proto`, `mxaccess_worker.proto`, `galaxy_repository.proto`). All other projects consume the generated types from here. Do not hand-edit anything under `Generated/`.
|
||||||
|
|
||||||
|
The worker must do all MXAccess COM calls on its dedicated STA thread, and the STA loop must pump Windows messages (`MsgWaitForMultipleObjectsEx` + `PeekMessage`/`DispatchMessage`) so MXAccess events deliver. A plain blocking queue on an STA is not enough.
|
||||||
|
|
||||||
|
## Build, Test, Run
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# Full solution build (gateway, worker, contracts, tests)
|
||||||
|
dotnet build src/MxGateway.sln
|
||||||
|
|
||||||
|
# Worker must be built x86 — the gateway looks for MxGateway.Worker.exe under bin\x86
|
||||||
|
dotnet build src/MxGateway.Worker/MxGateway.Worker.csproj -p:Platform=x86
|
||||||
|
|
||||||
|
# Gateway tests (no MXAccess required — uses FakeWorkerHarness)
|
||||||
|
dotnet test src/MxGateway.Tests/MxGateway.Tests.csproj
|
||||||
|
dotnet test src/MxGateway.Worker.Tests/MxGateway.Worker.Tests.csproj -p:Platform=x86
|
||||||
|
|
||||||
|
# Run gateway locally (defaults bound under MxGateway:* in src/MxGateway.Server/appsettings.json)
|
||||||
|
dotnet run --project src/MxGateway.Server/MxGateway.Server.csproj
|
||||||
|
|
||||||
|
# API-key admin CLI (same exe, "apikey" subcommand)
|
||||||
|
dotnet run --project src/MxGateway.Server/MxGateway.Server.csproj -- apikey create --display-name "dev" --scopes session,invoke,event,metadata,admin
|
||||||
|
```
|
||||||
|
|
||||||
|
Single test by name (xUnit `--filter`):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
dotnet test src/MxGateway.Tests/MxGateway.Tests.csproj --filter FullyQualifiedName~GatewayEndToEndFakeWorkerSmokeTests
|
||||||
|
```
|
||||||
|
|
||||||
|
Live MXAccess integration tests are **opt-in** because they need installed MXAccess COM and live provider state:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:MXGATEWAY_RUN_LIVE_MXACCESS_TESTS = "1"
|
||||||
|
dotnet test src/MxGateway.IntegrationTests/MxGateway.IntegrationTests.csproj --filter FullyQualifiedName~WorkerLiveMxAccessSmokeTests
|
||||||
|
```
|
||||||
|
|
||||||
|
Live LDAP tests use `MXGATEWAY_RUN_LIVE_LDAP_TESTS=1`. See `docs/GatewayTesting.md` for the full opt-in matrix and `LiveMxAccessFactAttribute` / `LiveLdapFactAttribute` for the gating logic.
|
||||||
|
|
||||||
|
## Clients
|
||||||
|
|
||||||
|
Each language client is in `clients/<lang>/` with its own README. They all consume the shared `.proto` files in `src/MxGateway.Contracts/Protos`:
|
||||||
|
|
||||||
|
- `clients/dotnet`: `dotnet build clients/dotnet/MxGateway.Client.sln`
|
||||||
|
- `clients/python`: `python -m pip install -e ".[dev]"; python -m pytest`
|
||||||
|
- `clients/rust`: `cargo test --workspace; cargo clippy --workspace --all-targets -- -D warnings`
|
||||||
|
- `clients/java`: `gradle test` (Java 21)
|
||||||
|
- Go client lives alongside as `mxgw-go` in the cross-language matrix
|
||||||
|
|
||||||
|
End-to-end matrix runner (needs running gateway + worker + valid API key):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:MXGATEWAY_API_KEY = "<api-key>"
|
||||||
|
powershell -ExecutionPolicy Bypass -File scripts/run-client-e2e-tests.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
## Repository-Specific Conventions
|
||||||
|
|
||||||
|
- **Build properties** (`src/Directory.Build.props`) enforce `Nullable=enable`, `TreatWarningsAsErrors=true`, latest analyzers, and `EnforceCodeStyleInBuild=true`. New warnings break the build — fix them, don't suppress unless the suppression has a narrow reason.
|
||||||
|
- **Style guides** in `docs/style-guides/` are authoritative. Follow `CSharpStyleGuide.md` for gateway/worker/.NET-client code: file-scoped namespaces, `sealed` by default, `Async` suffix on Task-returning methods, MXAccess-aligned names (`MxStatusProxy`, `ServerHandle`, `ItemHandle`, `HResult`).
|
||||||
|
- **MXAccess parity is the contract.** Don't "fix" surprising MXAccess behavior (e.g., `WriteSecured` failing before a value-bearing NMX body, distinct `OperationComplete` semantics, invalid-handle exceptions) unless the client explicitly opts into a non-parity mode. The installed MXAccess COM component is the baseline.
|
||||||
|
- **Don't synthesize events.** The gateway forwards only events the worker emits; it never invents `OperationComplete` from write completion or command replies.
|
||||||
|
- **One worker per session, one event subscriber per session** (v1). Multi-subscriber fan-out and reconnectable sessions are explicitly out of scope — see `docs/DesignDecisions.md`.
|
||||||
|
- **Gateway restart does not reattach orphan workers.** The first version terminates orphaned workers on startup; do not design code paths that assume reattachment.
|
||||||
|
- **No Blazor UI component libraries.** Dashboard uses local Bootstrap CSS/JS only — do not introduce MudBlazor, Radzen, FluentUI, etc.
|
||||||
|
- **Don't log secrets or full tag values by default.** API keys, passwords, `WriteSecured` payloads, and `AuthenticateUser` credentials must never reach logs. Value logging is opt-in and redacted.
|
||||||
|
- **Generated code** under `src/MxGateway.Contracts/Generated/`, `clients/*/generated*/`, `clients/python/src/mxgateway/generated/`, etc., is build output. Don't hand-edit. To regenerate, build the contracts project (`dotnet build src/MxGateway.Contracts/MxGateway.Contracts.csproj`) or run the per-client generation step in that client's README.
|
||||||
|
- **Documentation style** (`StyleGuide.md`): PascalCase filenames, no marketing language, present tense, explain *why* not *what*.
|
||||||
|
- **Update docs in the same change as the source.** When public APIs, contracts, configuration, build steps, security behavior, event shapes, value conversion, status mapping, or lifecycle rules change, the affected docs (`gateway.md`, `docs/`, client READMEs, design docs) must change in the same commit. Don't leave stale prose describing old behavior.
|
||||||
|
|
||||||
|
## Source Update Workflow
|
||||||
|
|
||||||
|
When source code changes, build and test the affected component before reporting work done. If the change crosses component boundaries, build each affected component — don't rely on a single top-level build:
|
||||||
|
|
||||||
|
| Changed area | Required verification |
|
||||||
|
|---|---|
|
||||||
|
| Contracts or `.proto` files | regenerate generated code, then build gateway, worker, and every generated client touched by the contract |
|
||||||
|
| Gateway server, sessions, workers, gRPC, dashboard, metrics | `dotnet build src/MxGateway.Server` and run affected gateway / fake-worker tests |
|
||||||
|
| Worker IPC, STA, MXAccess, conversion | `dotnet build src/MxGateway.Worker -p:Platform=x86` and run worker tests |
|
||||||
|
| .NET client | `dotnet build clients/dotnet/MxGateway.Client.sln` and run its tests |
|
||||||
|
| Go client | `gofmt`, `go build ./...`, `go test ./...` from `clients/go` |
|
||||||
|
| Rust client | `cargo fmt`, `cargo check --workspace`, `cargo test --workspace`, `cargo clippy --all-targets -- -D warnings` from `clients/rust` |
|
||||||
|
| Python client | `python -m pytest` from `clients/python` |
|
||||||
|
| Java client | `gradle test` from `clients/java` |
|
||||||
|
| Integration tests | run only when MXAccess COM, provider state, and external services are available; otherwise document why skipped |
|
||||||
|
|
||||||
|
## Design Sources To Consult Before Non-Trivial Changes
|
||||||
|
|
||||||
|
- `gateway.md` — top-level architecture, command/event surface, IPC envelope, STA thread model, fault handling.
|
||||||
|
- `glauth.md` — local LDAP server (GLAuth on `localhost:3893`, base DN `dc=lmxopcua,dc=local`) used for dev authn. Pre-provisioned users (`admin/admin123`, `readonly/readonly123`, etc.) and the role→capability mapping live there.
|
||||||
|
- `docs/DesignDecisions.md` — v1 choices (MXAccess COM target `LMXProxyServerClass` from `C:\Program Files (x86)\ArchestrA\Framework\Bin\ArchestrA.MXAccess.dll`, API-key-in-SQLite auth, fail-fast event backpressure, etc.).
|
||||||
|
- `docs/GatewayProcessDesign.md`, `docs/MxAccessWorkerInstanceDesign.md`, `docs/WorkerFrameProtocol.md`, `docs/WorkerProcessLauncher.md` — detailed component designs.
|
||||||
|
- `docs/GatewayConfiguration.md` — full `MxGateway:*` options bound by `GatewayOptions` and validated at startup by `GatewayOptionsValidator`.
|
||||||
|
- `docs/GatewayTesting.md` — fake worker harness, live MXAccess smoke, parity matrix, cross-language smoke matrix.
|
||||||
|
- `docs/ToolchainLinks.md` — installed compiler/SDK paths on this dev box (.NET 10.0.201, Go 1.26.2, Rust 1.95, Python 3.12.10, Temurin 21, protoc 34.1, etc.).
|
||||||
|
|
||||||
|
External analysis sources referenced by design docs:
|
||||||
|
|
||||||
|
- `C:\Users\dohertj2\Desktop\mxaccess` — MXAccess analysis project. Key files: `docs/MXAccess-Public-API.md` (COM class, ProgID, CLSID, method list, event signatures, `MxDataType`, `MxStatus`, `MXSTATUS_PROXY`), `docs/MXAccess-Reverse-Engineering.md` (installed runtime path, x86 COM constraints), `docs/Current-Sprint-State.md` (parity gaps), `src/MxTraceHarness/` (x86 harness using the real COM interop), `captures/` and `analysis/` (observed native behavior).
|
||||||
|
- `C:\Users\dohertj2\Desktop\lmxopcua\gr` — Galaxy Repository (`ZB` SQL DB) notes. Key files: `connectioninfo.md`, `layout.md`, `schema.md`, `queries/hierarchy.sql`, `queries/attributes.sql`, `queries/attributes_extended.sql`, `queries/change_detection.sql`. Connection is SQL Server `localhost`, database `ZB`, Windows Auth.
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
|
||||||
|
Gateway gRPC clients authenticate with an API key in metadata: `authorization: Bearer mxgw_<key-id>_<secret>`. Keys are stored hashed (with a peppered SHA) in a gateway-owned SQLite DB (default `C:\ProgramData\MxGateway\gateway-auth.db`). Scopes (`session`, `invoke`, `event`, `metadata`, `admin`) gate specific RPCs; missing → `Unauthenticated`, insufficient → `PermissionDenied`. The `apikey` subcommand on the server exe manages keys; see `src/MxGateway.Server/Security/Authentication/`.
|
||||||
|
|
||||||
|
Dashboard auth is LDAP-backed (separate from the gRPC API-key model). `/login` binds against `MxGateway:Ldap` and maps the user's LDAP groups to `Admin` or `Viewer` via `MxGateway:Dashboard:GroupToRole`, then issues an HTTP-only secure `__Host-MxGatewayDashboard` cookie. SignalR hubs at `/hubs/{snapshot,alarms,events}` accept either the cookie or a 30-minute bearer minted at `/hubs/token`. `Dashboard:AllowAnonymousLocalhost` bypasses auth on loopback when enabled.
|
||||||
|
|
||||||
|
## Process / Platform Notes
|
||||||
|
|
||||||
|
- Working tree is on Windows (`C:\Users\dohertj2\Desktop\mxaccessgw`). PowerShell is the native shell for tooling commands; bash is fine for git/grep/find.
|
||||||
|
- The worker reference to `ArchestrA.MXAccess.dll` uses an absolute `HintPath` to `C:\Program Files (x86)\ArchestrA\Framework\Bin\ArchestrA.MXAccess.dll`. The worker only builds where MXAccess is installed (this dev box).
|
||||||
|
- The repo is not a git repository at the top level — there's no `.git` directory in the working tree.
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
# Code Review Process
|
||||||
|
|
||||||
|
This document describes how to perform a comprehensive, per-module code review of
|
||||||
|
the `mxaccessgw` codebase and how to track findings to resolution.
|
||||||
|
|
||||||
|
A **module** is one buildable project under `src/` (e.g. `src/ZB.MOM.WW.MxGateway.Worker`)
|
||||||
|
or one language client under `clients/` (e.g. `clients/rust`). Each module has
|
||||||
|
its own folder under `code-reviews/` containing a single `findings.md`.
|
||||||
|
|
||||||
|
## 1. Before you start
|
||||||
|
|
||||||
|
1. Pick the module to review. Its folder is `code-reviews/<Module>/`:
|
||||||
|
- For a `src/` project, `<Module>` is the project name with the `ZB.MOM.WW.MxGateway.`
|
||||||
|
prefix stripped — `src/ZB.MOM.WW.MxGateway.Server` is reviewed in `code-reviews/Server/`.
|
||||||
|
- For a language client, `<Module>` is `Client.<Lang>` — `clients/rust` is
|
||||||
|
reviewed in `code-reviews/Client.Rust/`.
|
||||||
|
2. Identify the design context for the module:
|
||||||
|
- `gateway.md` — top-level architecture, command/event surface, IPC envelope,
|
||||||
|
STA thread model, fault handling.
|
||||||
|
- The relevant component design docs under `docs/` (e.g.
|
||||||
|
`docs/MxAccessWorkerInstanceDesign.md`, `docs/GatewayProcessDesign.md`,
|
||||||
|
`docs/Sessions.md`, `docs/Authentication.md`, `docs/GalaxyRepository.md`).
|
||||||
|
- `docs/DesignDecisions.md` for the v1 design choices.
|
||||||
|
- The **Repository-Specific Conventions** and **Process / Platform Notes** in
|
||||||
|
`CLAUDE.md`.
|
||||||
|
3. Record the exact commit being reviewed: `git rev-parse --short HEAD`. Every
|
||||||
|
review is a snapshot — a finding only means something relative to a known
|
||||||
|
commit.
|
||||||
|
4. Open `code-reviews/<Module>/findings.md` and fill in the header table
|
||||||
|
(reviewer, date, commit SHA, status).
|
||||||
|
|
||||||
|
## 2. Review checklist
|
||||||
|
|
||||||
|
Work through **every** category below for the module. A comprehensive review
|
||||||
|
means the checklist is completed even where it produces no findings — record
|
||||||
|
"No issues found" for a category rather than leaving it ambiguous.
|
||||||
|
|
||||||
|
1. **Correctness & logic bugs** — off-by-one, null handling, incorrect
|
||||||
|
conditionals, misuse of APIs, broken edge cases.
|
||||||
|
2. **mxaccessgw conventions** — the rules in `CLAUDE.md` and the style guides
|
||||||
|
under `docs/style-guides/`: the gateway never instantiates MXAccess COM
|
||||||
|
directly; all MXAccess COM calls run on the worker's dedicated STA thread and
|
||||||
|
the STA loop pumps Windows messages; IPC uses one bidirectional named pipe per
|
||||||
|
worker carrying length-prefixed `WorkerEnvelope` protobuf frames; MXAccess
|
||||||
|
parity is the contract (don't "fix" surprising MXAccess behaviour, never
|
||||||
|
synthesize events); one worker and one event subscriber per session; the
|
||||||
|
gateway terminates orphan workers on startup and does not reattach; C# style
|
||||||
|
(file-scoped namespaces, `sealed` by default, `Async` suffix, MXAccess-aligned
|
||||||
|
names); no Blazor UI component libraries; no logging of secrets or full tag
|
||||||
|
values; generated code is never hand-edited.
|
||||||
|
3. **Concurrency & thread safety** — shared mutable state, STA affinity, race
|
||||||
|
conditions, correct use of `async`/`await`, locking, disposal races.
|
||||||
|
4. **Error handling & resilience** — exception paths, worker crash / reconnect
|
||||||
|
handling, fail-fast event backpressure, transient vs permanent error
|
||||||
|
classification, graceful degradation, correct gRPC status codes.
|
||||||
|
5. **Security** — authentication/authorization checks, API-key scope enforcement,
|
||||||
|
input validation, SQL injection in the Galaxy Repository RPCs, secret
|
||||||
|
handling, the dashboard anonymous-localhost bypass, logging of sensitive data.
|
||||||
|
6. **Performance & resource management** — `IDisposable` disposal, pipe / stream
|
||||||
|
/ COM lifetimes, buffering and back-pressure, unnecessary allocations on hot
|
||||||
|
paths, N+1 queries.
|
||||||
|
7. **Design-document adherence** — does the code match `gateway.md`, the relevant
|
||||||
|
`docs/` component designs, `docs/DesignDecisions.md`, and `CLAUDE.md`? Flag
|
||||||
|
both code that drifts from the design and design docs that are now stale.
|
||||||
|
8. **Code organization & conventions** — namespace hierarchy, project layout, the
|
||||||
|
Options pattern, separation of concerns, additive-only contract evolution.
|
||||||
|
9. **Testing coverage** — are the module's behaviours covered by tests
|
||||||
|
(`src/ZB.MOM.WW.MxGateway.Tests`, `src/ZB.MOM.WW.MxGateway.Worker.Tests`,
|
||||||
|
`src/ZB.MOM.WW.MxGateway.IntegrationTests`)? Note untested critical paths and missing
|
||||||
|
edge-case tests.
|
||||||
|
10. **Documentation & comments** — XML doc accuracy, misleading or stale comments,
|
||||||
|
undocumented non-obvious behaviour.
|
||||||
|
|
||||||
|
## 3. Recording findings
|
||||||
|
|
||||||
|
Add one entry per finding to the `## Findings` section of the module's
|
||||||
|
`findings.md`, using the entry format in
|
||||||
|
[`_template/findings.md`](code-reviews/_template/findings.md).
|
||||||
|
|
||||||
|
- **Finding ID** — `<Module>-NNN`, numbered sequentially within the module and
|
||||||
|
never reused (e.g. `Worker-001`). IDs are permanent even after resolution.
|
||||||
|
- **Severity:**
|
||||||
|
- **Critical** — data loss, security breach, crash/deadlock, or outage.
|
||||||
|
- **High** — incorrect behaviour with significant impact; no safe workaround.
|
||||||
|
- **Medium** — incorrect or risky behaviour with limited impact or a workaround.
|
||||||
|
- **Low** — minor issues, style, maintainability, documentation.
|
||||||
|
- **Category** — one of the 10 checklist categories above.
|
||||||
|
- **Location** — `file:line` (clickable), or a list of locations.
|
||||||
|
- **Description** — what is wrong and why it matters.
|
||||||
|
- **Recommendation** — concrete suggested fix.
|
||||||
|
|
||||||
|
After recording findings, update the module header table (status, open-finding
|
||||||
|
count) and regenerate the base README (step 5).
|
||||||
|
|
||||||
|
## 4. Marking an item resolved
|
||||||
|
|
||||||
|
Findings are **never deleted** — they are an audit trail. To close one, change
|
||||||
|
its **Status** and complete the **Resolution** field:
|
||||||
|
|
||||||
|
- `Open` — newly recorded, not yet addressed.
|
||||||
|
- `In Progress` — a fix is actively being worked on.
|
||||||
|
- `Resolved` — fixed. The Resolution field must state the fixing commit SHA, the
|
||||||
|
date, and a one-line description of the fix.
|
||||||
|
- `Won't Fix` — intentionally not fixed. The Resolution field must justify why.
|
||||||
|
- `Deferred` — valid but postponed. The Resolution field must say what it is
|
||||||
|
waiting on (e.g. a tracked issue or a later milestone).
|
||||||
|
|
||||||
|
`Resolved`, `Won't Fix`, and `Deferred` findings are all considered **closed**.
|
||||||
|
`Open` and `In Progress` are **pending** and appear in the base README's Pending
|
||||||
|
Findings table.
|
||||||
|
|
||||||
|
## 5. Updating the base README
|
||||||
|
|
||||||
|
`code-reviews/README.md` holds the single cross-module view (the Module Status
|
||||||
|
table and the Pending / Closed Findings tables). It is **generated** from the
|
||||||
|
per-module `findings.md` files — do not edit it by hand.
|
||||||
|
|
||||||
|
After any review or status change, regenerate it:
|
||||||
|
|
||||||
|
```
|
||||||
|
python code-reviews/regen-readme.py
|
||||||
|
```
|
||||||
|
|
||||||
|
`regen-readme.py --check` exits non-zero if `README.md` is stale, if a module
|
||||||
|
header's `Open findings` count disagrees with its finding statuses, or if a
|
||||||
|
finding carries an unrecognised Status value. The PowerShell wrapper
|
||||||
|
`scripts/check-code-reviews-readme.ps1` runs that check and is the intended hook
|
||||||
|
for CI or a pre-commit step.
|
||||||
|
|
||||||
|
> The repo's installed `python` is the real interpreter; the bare `python3`
|
||||||
|
> alias resolves to the Windows Store stub and fails. Use `python`.
|
||||||
|
|
||||||
|
The per-module `findings.md` files are the source of truth; `README.md` is the
|
||||||
|
aggregated index and must always agree with them — which the script guarantees.
|
||||||
|
|
||||||
|
## 6. Re-reviewing a module
|
||||||
|
|
||||||
|
Re-reviews append to the same `findings.md`. Update the header to the new commit
|
||||||
|
and date, continue the finding numbering from the last used ID, and leave prior
|
||||||
|
findings (including closed ones) in place as history.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<!-- Shared package metadata for clients/dotnet/. Individual projects opt in via <IsPackable>true</IsPackable>. -->
|
||||||
|
<Authors>Joseph Doherty</Authors>
|
||||||
|
<Company>ZB MOM WW</Company>
|
||||||
|
<Copyright>Copyright (c) ZB MOM WW. All rights reserved.</Copyright>
|
||||||
|
<Product>MxAccessGateway Client</Product>
|
||||||
|
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/mxaccessgw</RepositoryUrl>
|
||||||
|
<RepositoryType>git</RepositoryType>
|
||||||
|
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/mxaccessgw</PackageProjectUrl>
|
||||||
|
<PackageTags>mxaccess;mxgateway;grpc;client;archestra</PackageTags>
|
||||||
|
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
|
||||||
|
<!-- Versioning: bump per release. Symbols ship as snupkg. -->
|
||||||
|
<Version>0.1.0</Version>
|
||||||
|
<IncludeSymbols>true</IncludeSymbols>
|
||||||
|
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
|
||||||
|
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||||
|
<!-- Default: do NOT pack. Each project opts in. -->
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -6,8 +6,8 @@ Provide an idiomatic .NET 10 C# client library for MXAccess Gateway, plus a test
|
|||||||
CLI and unit tests. This client is for modern .NET callers and must not load
|
CLI and unit tests. This client is for modern .NET callers and must not load
|
||||||
MXAccess COM.
|
MXAccess COM.
|
||||||
|
|
||||||
Follow the [C# Style Guide](./style-guides/CSharpStyleGuide.md) for
|
Follow the [C# Style Guide](../../docs/style-guides/CSharpStyleGuide.md) for
|
||||||
handwritten code and the [Protobuf Style Guide](./style-guides/ProtobufStyleGuide.md)
|
handwritten code and the [Protobuf Style Guide](../../docs/style-guides/ProtobufStyleGuide.md)
|
||||||
for generated contract inputs.
|
for generated contract inputs.
|
||||||
|
|
||||||
## Projects
|
## Projects
|
||||||
@@ -16,9 +16,9 @@ Recommended layout:
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
clients/dotnet/
|
clients/dotnet/
|
||||||
MxGateway.Client.sln
|
ZB.MOM.WW.MxGateway.Client.slnx
|
||||||
MxGateway.Client/
|
ZB.MOM.WW.MxGateway.Client/
|
||||||
MxGateway.Client.csproj
|
ZB.MOM.WW.MxGateway.Client.csproj
|
||||||
GatewayClient.cs
|
GatewayClient.cs
|
||||||
MxGatewaySession.cs
|
MxGatewaySession.cs
|
||||||
MxGatewayClientOptions.cs
|
MxGatewayClientOptions.cs
|
||||||
@@ -26,14 +26,14 @@ clients/dotnet/
|
|||||||
Conversion/
|
Conversion/
|
||||||
Errors/
|
Errors/
|
||||||
Generated/
|
Generated/
|
||||||
MxGateway.Client.Cli/
|
ZB.MOM.WW.MxGateway.Client.Cli/
|
||||||
MxGateway.Client.Cli.csproj
|
ZB.MOM.WW.MxGateway.Client.Cli.csproj
|
||||||
Program.cs
|
Program.cs
|
||||||
Commands/
|
Commands/
|
||||||
MxGateway.Client.Tests/
|
ZB.MOM.WW.MxGateway.Client.Tests/
|
||||||
MxGateway.Client.Tests.csproj
|
ZB.MOM.WW.MxGateway.Client.Tests.csproj
|
||||||
MxGateway.Client.IntegrationTests/
|
ZB.MOM.WW.MxGateway.Client.IntegrationTests/
|
||||||
MxGateway.Client.IntegrationTests.csproj
|
ZB.MOM.WW.MxGateway.Client.IntegrationTests.csproj
|
||||||
```
|
```
|
||||||
|
|
||||||
Target framework:
|
Target framework:
|
||||||
@@ -43,7 +43,7 @@ Target framework:
|
|||||||
```
|
```
|
||||||
|
|
||||||
The scaffold uses a project reference to
|
The scaffold uses a project reference to
|
||||||
`src/MxGateway.Contracts/MxGateway.Contracts.csproj` for generated protobuf and
|
`src/ZB.MOM.WW.MxGateway.Contracts/ZB.MOM.WW.MxGateway.Contracts.csproj` for generated protobuf and
|
||||||
gRPC types. `clients/dotnet/generated` remains reserved for client-local
|
gRPC types. `clients/dotnet/generated` remains reserved for client-local
|
||||||
generator output if the .NET client later needs to decouple from the contracts
|
generator output if the .NET client later needs to decouple from the contracts
|
||||||
project.
|
project.
|
||||||
@@ -83,6 +83,12 @@ public sealed class MxGatewaySession : IAsyncDisposable
|
|||||||
public Task<int> AddItem2Async(int serverHandle, string item, string context, CancellationToken ct = default);
|
public Task<int> AddItem2Async(int serverHandle, string item, string context, CancellationToken ct = default);
|
||||||
public Task AdviseAsync(int serverHandle, int itemHandle, CancellationToken ct = default);
|
public Task AdviseAsync(int serverHandle, int itemHandle, CancellationToken ct = default);
|
||||||
public Task UnAdviseAsync(int serverHandle, int itemHandle, CancellationToken ct = default);
|
public Task UnAdviseAsync(int serverHandle, int itemHandle, CancellationToken ct = default);
|
||||||
|
public Task<IReadOnlyList<SubscribeResult>> AddItemBulkAsync(int serverHandle, IReadOnlyList<string> tagAddresses, CancellationToken ct = default);
|
||||||
|
public Task<IReadOnlyList<SubscribeResult>> AdviseItemBulkAsync(int serverHandle, IReadOnlyList<int> itemHandles, CancellationToken ct = default);
|
||||||
|
public Task<IReadOnlyList<SubscribeResult>> RemoveItemBulkAsync(int serverHandle, IReadOnlyList<int> itemHandles, CancellationToken ct = default);
|
||||||
|
public Task<IReadOnlyList<SubscribeResult>> UnAdviseItemBulkAsync(int serverHandle, IReadOnlyList<int> itemHandles, CancellationToken ct = default);
|
||||||
|
public Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(int serverHandle, IReadOnlyList<string> tagAddresses, CancellationToken ct = default);
|
||||||
|
public Task<IReadOnlyList<SubscribeResult>> UnsubscribeBulkAsync(int serverHandle, IReadOnlyList<int> itemHandles, CancellationToken ct = default);
|
||||||
public Task WriteAsync(int serverHandle, int itemHandle, MxValue value, int userId, CancellationToken ct = default);
|
public Task WriteAsync(int serverHandle, int itemHandle, MxValue value, int userId, CancellationToken ct = default);
|
||||||
public IAsyncEnumerable<MxEvent> StreamEventsAsync(CancellationToken ct = default);
|
public IAsyncEnumerable<MxEvent> StreamEventsAsync(CancellationToken ct = default);
|
||||||
public Task CloseAsync(CancellationToken ct = default);
|
public Task CloseAsync(CancellationToken ct = default);
|
||||||
@@ -104,10 +110,17 @@ public sealed class MxGatewayClientOptions
|
|||||||
public string? ServerNameOverride { get; init; }
|
public string? ServerNameOverride { get; init; }
|
||||||
public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10);
|
public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10);
|
||||||
public TimeSpan DefaultCallTimeout { get; init; } = TimeSpan.FromSeconds(30);
|
public TimeSpan DefaultCallTimeout { get; init; } = TimeSpan.FromSeconds(30);
|
||||||
|
public MxGatewayClientRetryOptions Retry { get; init; } = new();
|
||||||
public ILoggerFactory? LoggerFactory { get; init; }
|
public ILoggerFactory? LoggerFactory { get; init; }
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The .NET client applies a bounded Polly retry policy only to idempotent calls:
|
||||||
|
`CloseSession` and diagnostic `Invoke` commands such as `Ping`,
|
||||||
|
`GetSessionState`, and `GetWorkerInfo`. It does not retry `OpenSession`, event
|
||||||
|
streams, writes, secured writes, authentication, registration, item management,
|
||||||
|
or subscription changes because those calls can partially succeed in MXAccess.
|
||||||
|
|
||||||
API key may be loaded from `MXGATEWAY_API_KEY` by the CLI, not implicitly by the
|
API key may be loaded from `MXGATEWAY_API_KEY` by the CLI, not implicitly by the
|
||||||
library constructor unless a helper explicitly says it does that.
|
library constructor unless a helper explicitly says it does that.
|
||||||
|
|
||||||
@@ -153,7 +166,7 @@ reply.EnsureMxAccessSuccess();
|
|||||||
|
|
||||||
## Test CLI
|
## Test CLI
|
||||||
|
|
||||||
Project: `MxGateway.Client.Cli`.
|
Project: `ZB.MOM.WW.MxGateway.Client.Cli`.
|
||||||
|
|
||||||
Command examples:
|
Command examples:
|
||||||
|
|
||||||
@@ -198,3 +211,10 @@ MXGATEWAY_TEST_ITEM=<item>
|
|||||||
|
|
||||||
Integration smoke should open, register, add, advise, stream for bounded time,
|
Integration smoke should open, register, add, advise, stream for bounded time,
|
||||||
and close.
|
and close.
|
||||||
|
|
||||||
|
## Related Documentation
|
||||||
|
|
||||||
|
- [Client Libraries Detailed Design](../../docs/ClientLibrariesDesign.md)
|
||||||
|
- [Client Proto Generation](../../docs/ClientProtoGeneration.md)
|
||||||
|
- [Client Packaging](../../docs/ClientPackaging.md)
|
||||||
|
- [C# Style Guide](../../docs/style-guides/CSharpStyleGuide.md)
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client.Cli;
|
|
||||||
|
|
||||||
public interface IMxGatewayCliClient : IAsyncDisposable
|
|
||||||
{
|
|
||||||
Task<OpenSessionReply> OpenSessionAsync(
|
|
||||||
OpenSessionRequest request,
|
|
||||||
CancellationToken cancellationToken);
|
|
||||||
|
|
||||||
Task<CloseSessionReply> CloseSessionAsync(
|
|
||||||
CloseSessionRequest request,
|
|
||||||
CancellationToken cancellationToken);
|
|
||||||
|
|
||||||
Task<MxCommandReply> InvokeAsync(
|
|
||||||
MxCommandRequest request,
|
|
||||||
CancellationToken cancellationToken);
|
|
||||||
|
|
||||||
IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
|
||||||
StreamEventsRequest request,
|
|
||||||
CancellationToken cancellationToken);
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
using MxGateway.Client;
|
|
||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client.Cli;
|
|
||||||
|
|
||||||
internal sealed class MxGatewayCliClientAdapter(MxGatewayClient client) : IMxGatewayCliClient
|
|
||||||
{
|
|
||||||
public Task<OpenSessionReply> OpenSessionAsync(
|
|
||||||
OpenSessionRequest request,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return client.OpenSessionRawAsync(request, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<CloseSessionReply> CloseSessionAsync(
|
|
||||||
CloseSessionRequest request,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return client.CloseSessionRawAsync(request, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> InvokeAsync(
|
|
||||||
MxCommandRequest request,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return client.InvokeAsync(request, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
|
||||||
StreamEventsRequest request,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return client.StreamEventsAsync(request, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public ValueTask DisposeAsync()
|
|
||||||
{
|
|
||||||
return client.DisposeAsync();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
namespace MxGateway.Client.Cli;
|
|
||||||
|
|
||||||
internal static class MxGatewayCliSecretRedactor
|
|
||||||
{
|
|
||||||
public static string Redact(string value, string? apiKey)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(apiKey))
|
|
||||||
{
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return value.Replace(apiKey, "[redacted]", StringComparison.Ordinal);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,744 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
using System.Text.Json;
|
|
||||||
using Google.Protobuf;
|
|
||||||
using MxGateway.Client;
|
|
||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client.Cli;
|
|
||||||
|
|
||||||
public static class MxGatewayClientCli
|
|
||||||
{
|
|
||||||
private static readonly JsonFormatter ProtobufJsonFormatter = JsonFormatter.Default;
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
|
||||||
|
|
||||||
public static int Run(
|
|
||||||
string[] args,
|
|
||||||
TextWriter standardOutput,
|
|
||||||
TextWriter standardError)
|
|
||||||
{
|
|
||||||
return RunAsync(args, standardOutput, standardError)
|
|
||||||
.GetAwaiter()
|
|
||||||
.GetResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Task<int> RunAsync(
|
|
||||||
string[] args,
|
|
||||||
TextWriter standardOutput,
|
|
||||||
TextWriter standardError,
|
|
||||||
Func<MxGatewayClientOptions, IMxGatewayCliClient>? clientFactory = null)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(args);
|
|
||||||
ArgumentNullException.ThrowIfNull(standardOutput);
|
|
||||||
ArgumentNullException.ThrowIfNull(standardError);
|
|
||||||
|
|
||||||
return RunCoreAsync(
|
|
||||||
args,
|
|
||||||
standardOutput,
|
|
||||||
standardError,
|
|
||||||
clientFactory ?? CreateDefaultClient);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<int> RunCoreAsync(
|
|
||||||
string[] args,
|
|
||||||
TextWriter standardOutput,
|
|
||||||
TextWriter standardError,
|
|
||||||
Func<MxGatewayClientOptions, IMxGatewayCliClient> clientFactory)
|
|
||||||
{
|
|
||||||
if (args.Length is 0 || IsHelp(args[0]))
|
|
||||||
{
|
|
||||||
WriteUsage(standardOutput);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
string command = args[0].ToLowerInvariant();
|
|
||||||
CliArguments arguments = new(args.Skip(1));
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (command is "version")
|
|
||||||
{
|
|
||||||
WriteVersion(arguments, standardOutput);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!IsKnownGatewayCommand(command))
|
|
||||||
{
|
|
||||||
return WriteUnknownCommand(command, standardError);
|
|
||||||
}
|
|
||||||
|
|
||||||
await using IMxGatewayCliClient client = clientFactory(CreateOptions(arguments));
|
|
||||||
using CancellationTokenSource cancellation = CreateCancellation(arguments);
|
|
||||||
|
|
||||||
return command switch
|
|
||||||
{
|
|
||||||
"open-session" => await OpenSessionAsync(arguments, client, standardOutput, cancellation.Token)
|
|
||||||
.ConfigureAwait(false),
|
|
||||||
"close-session" => await CloseSessionAsync(arguments, client, standardOutput, cancellation.Token)
|
|
||||||
.ConfigureAwait(false),
|
|
||||||
"ping" => await PingAsync(arguments, client, standardOutput, cancellation.Token)
|
|
||||||
.ConfigureAwait(false),
|
|
||||||
"register" => await RegisterAsync(arguments, client, standardOutput, cancellation.Token)
|
|
||||||
.ConfigureAwait(false),
|
|
||||||
"add-item" => await AddItemAsync(arguments, client, standardOutput, cancellation.Token)
|
|
||||||
.ConfigureAwait(false),
|
|
||||||
"advise" => await AdviseAsync(arguments, client, standardOutput, cancellation.Token)
|
|
||||||
.ConfigureAwait(false),
|
|
||||||
"stream-events" => await StreamEventsAsync(arguments, client, standardOutput, cancellation.Token)
|
|
||||||
.ConfigureAwait(false),
|
|
||||||
"write" => await WriteAsync(arguments, client, standardOutput, cancellation.Token)
|
|
||||||
.ConfigureAwait(false),
|
|
||||||
"write2" => await Write2Async(arguments, client, standardOutput, cancellation.Token)
|
|
||||||
.ConfigureAwait(false),
|
|
||||||
"smoke" => await SmokeAsync(arguments, client, standardOutput, cancellation.Token)
|
|
||||||
.ConfigureAwait(false),
|
|
||||||
_ => WriteUnknownCommand(command, standardError),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
|
||||||
{
|
|
||||||
string? apiKey = arguments.GetOptional("api-key");
|
|
||||||
string message = MxGatewayCliSecretRedactor.Redact(exception.Message, apiKey);
|
|
||||||
|
|
||||||
if (arguments.HasFlag("json"))
|
|
||||||
{
|
|
||||||
standardError.WriteLine(JsonSerializer.Serialize(
|
|
||||||
new { error = message, type = exception.GetType().Name },
|
|
||||||
JsonOptions));
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
standardError.WriteLine(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static IMxGatewayCliClient CreateDefaultClient(MxGatewayClientOptions options)
|
|
||||||
{
|
|
||||||
return new MxGatewayCliClientAdapter(MxGatewayClient.Create(options));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static MxGatewayClientOptions CreateOptions(CliArguments arguments)
|
|
||||||
{
|
|
||||||
string endpoint = arguments.GetOptional("endpoint")
|
|
||||||
?? Environment.GetEnvironmentVariable("MXGATEWAY_ENDPOINT")
|
|
||||||
?? "http://localhost:5000";
|
|
||||||
|
|
||||||
string apiKey = ResolveApiKey(arguments);
|
|
||||||
|
|
||||||
return new MxGatewayClientOptions
|
|
||||||
{
|
|
||||||
Endpoint = new Uri(endpoint, UriKind.Absolute),
|
|
||||||
ApiKey = apiKey,
|
|
||||||
UseTls = arguments.HasFlag("tls")
|
|
||||||
|| endpoint.StartsWith("https://", StringComparison.OrdinalIgnoreCase),
|
|
||||||
DefaultCallTimeout = arguments.GetDuration("timeout", TimeSpan.FromSeconds(30)),
|
|
||||||
ConnectTimeout = arguments.GetDuration("connect-timeout", TimeSpan.FromSeconds(10)),
|
|
||||||
CaCertificatePath = arguments.GetOptional("ca-file"),
|
|
||||||
ServerNameOverride = arguments.GetOptional("server-name"),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string ResolveApiKey(CliArguments arguments)
|
|
||||||
{
|
|
||||||
string? apiKey = arguments.GetOptional("api-key");
|
|
||||||
if (!string.IsNullOrWhiteSpace(apiKey))
|
|
||||||
{
|
|
||||||
return apiKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
string apiKeyEnvironmentName = arguments.GetOptional("api-key-env")
|
|
||||||
?? "MXGATEWAY_API_KEY";
|
|
||||||
|
|
||||||
apiKey = Environment.GetEnvironmentVariable(apiKeyEnvironmentName);
|
|
||||||
if (!string.IsNullOrWhiteSpace(apiKey))
|
|
||||||
{
|
|
||||||
return apiKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new ArgumentException(
|
|
||||||
$"Gateway API key is required. Pass --api-key or set {apiKeyEnvironmentName}.");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static CancellationTokenSource CreateCancellation(CliArguments arguments)
|
|
||||||
{
|
|
||||||
var cancellation = new CancellationTokenSource();
|
|
||||||
TimeSpan timeout = arguments.GetDuration("timeout", TimeSpan.FromSeconds(30));
|
|
||||||
cancellation.CancelAfter(timeout);
|
|
||||||
return cancellation;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<int> OpenSessionAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return WriteReplyAsync(
|
|
||||||
client.OpenSessionAsync(
|
|
||||||
new OpenSessionRequest
|
|
||||||
{
|
|
||||||
ClientSessionName = arguments.GetOptional("client-name") ?? "mxgw-dotnet-cli",
|
|
||||||
ClientCorrelationId = CreateCorrelationId(),
|
|
||||||
RequestedBackend = arguments.GetOptional("backend") ?? string.Empty,
|
|
||||||
},
|
|
||||||
cancellationToken),
|
|
||||||
arguments,
|
|
||||||
output);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<int> CloseSessionAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return WriteReplyAsync(
|
|
||||||
client.CloseSessionAsync(
|
|
||||||
new CloseSessionRequest
|
|
||||||
{
|
|
||||||
SessionId = arguments.GetRequired("session-id"),
|
|
||||||
ClientCorrelationId = CreateCorrelationId(),
|
|
||||||
},
|
|
||||||
cancellationToken),
|
|
||||||
arguments,
|
|
||||||
output);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<int> PingAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return InvokeAndWriteAsync(
|
|
||||||
arguments,
|
|
||||||
client,
|
|
||||||
output,
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Ping,
|
|
||||||
Ping = new PingCommand { Message = arguments.GetOptional("message") ?? "ping" },
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<int> RegisterAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return InvokeAndWriteAsync(
|
|
||||||
arguments,
|
|
||||||
client,
|
|
||||||
output,
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Register,
|
|
||||||
Register = new RegisterCommand { ClientName = arguments.GetOptional("client-name") ?? "mxgw-dotnet-cli" },
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<int> AddItemAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return InvokeAndWriteAsync(
|
|
||||||
arguments,
|
|
||||||
client,
|
|
||||||
output,
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.AddItem,
|
|
||||||
AddItem = new AddItemCommand
|
|
||||||
{
|
|
||||||
ServerHandle = arguments.GetInt32("server-handle"),
|
|
||||||
ItemDefinition = arguments.GetRequired("item"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<int> AdviseAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return InvokeAndWriteAsync(
|
|
||||||
arguments,
|
|
||||||
client,
|
|
||||||
output,
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Advise,
|
|
||||||
Advise = new AdviseCommand
|
|
||||||
{
|
|
||||||
ServerHandle = arguments.GetInt32("server-handle"),
|
|
||||||
ItemHandle = arguments.GetInt32("item-handle"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<int> WriteAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return InvokeAndWriteAsync(
|
|
||||||
arguments,
|
|
||||||
client,
|
|
||||||
output,
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Write,
|
|
||||||
Write = new WriteCommand
|
|
||||||
{
|
|
||||||
ServerHandle = arguments.GetInt32("server-handle"),
|
|
||||||
ItemHandle = arguments.GetInt32("item-handle"),
|
|
||||||
UserId = arguments.GetInt32("user-id", 0),
|
|
||||||
Value = ParseValue(arguments),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<int> Write2Async(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return InvokeAndWriteAsync(
|
|
||||||
arguments,
|
|
||||||
client,
|
|
||||||
output,
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Write2,
|
|
||||||
Write2 = new Write2Command
|
|
||||||
{
|
|
||||||
ServerHandle = arguments.GetInt32("server-handle"),
|
|
||||||
ItemHandle = arguments.GetInt32("item-handle"),
|
|
||||||
UserId = arguments.GetInt32("user-id", 0),
|
|
||||||
Value = ParseValue(arguments),
|
|
||||||
TimestampValue = ParseTimestampValue(arguments),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<int> StreamEventsAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var events = new List<MxEvent>();
|
|
||||||
uint maxEvents = arguments.GetUInt32("max-events", 0);
|
|
||||||
uint eventCount = 0;
|
|
||||||
var request = new StreamEventsRequest
|
|
||||||
{
|
|
||||||
SessionId = arguments.GetRequired("session-id"),
|
|
||||||
AfterWorkerSequence = arguments.GetUInt64("after-worker-sequence", 0),
|
|
||||||
};
|
|
||||||
|
|
||||||
await foreach (MxEvent gatewayEvent in client.StreamEventsAsync(request, cancellationToken)
|
|
||||||
.WithCancellation(cancellationToken)
|
|
||||||
.ConfigureAwait(false))
|
|
||||||
{
|
|
||||||
if (arguments.HasFlag("json"))
|
|
||||||
{
|
|
||||||
events.Add(gatewayEvent);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
output.WriteLine(ProtobufJsonFormatter.Format(gatewayEvent));
|
|
||||||
}
|
|
||||||
|
|
||||||
eventCount++;
|
|
||||||
if (maxEvents > 0 && eventCount >= maxEvents)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (arguments.HasFlag("json"))
|
|
||||||
{
|
|
||||||
output.WriteLine(JsonSerializer.Serialize(
|
|
||||||
new { events = events.Select(EventToJsonElement).ToArray() },
|
|
||||||
JsonOptions));
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<int> SmokeAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
OpenSessionReply? openReply = null;
|
|
||||||
CloseSessionReply? closeReply = null;
|
|
||||||
var commandReplies = new List<MxCommandReply>();
|
|
||||||
var events = new List<MxEvent>();
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
openReply = await client.OpenSessionAsync(
|
|
||||||
new OpenSessionRequest
|
|
||||||
{
|
|
||||||
ClientSessionName = arguments.GetOptional("client-name") ?? "mxgw-dotnet-smoke",
|
|
||||||
ClientCorrelationId = CreateCorrelationId(),
|
|
||||||
},
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
int serverHandle = await InvokeForHandleAsync(
|
|
||||||
arguments,
|
|
||||||
client,
|
|
||||||
openReply.SessionId,
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Register,
|
|
||||||
Register = new RegisterCommand { ClientName = arguments.GetOptional("client-name") ?? "mxgw-dotnet-smoke" },
|
|
||||||
},
|
|
||||||
reply => reply.Register?.ServerHandle ?? reply.ReturnValue.Int32Value,
|
|
||||||
commandReplies,
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
int itemHandle = await InvokeForHandleAsync(
|
|
||||||
arguments,
|
|
||||||
client,
|
|
||||||
openReply.SessionId,
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.AddItem,
|
|
||||||
AddItem = new AddItemCommand
|
|
||||||
{
|
|
||||||
ServerHandle = serverHandle,
|
|
||||||
ItemDefinition = arguments.GetRequired("item"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
reply => reply.AddItem?.ItemHandle ?? reply.ReturnValue.Int32Value,
|
|
||||||
commandReplies,
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
commandReplies.Add(await InvokeAndEnsureAsync(
|
|
||||||
client,
|
|
||||||
CreateCommandRequest(
|
|
||||||
openReply.SessionId,
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Advise,
|
|
||||||
Advise = new AdviseCommand
|
|
||||||
{
|
|
||||||
ServerHandle = serverHandle,
|
|
||||||
ItemHandle = itemHandle,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false));
|
|
||||||
|
|
||||||
if (arguments.GetOptional("value") is not null)
|
|
||||||
{
|
|
||||||
commandReplies.Add(await InvokeAndEnsureAsync(
|
|
||||||
client,
|
|
||||||
CreateCommandRequest(
|
|
||||||
openReply.SessionId,
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Write,
|
|
||||||
Write = new WriteCommand
|
|
||||||
{
|
|
||||||
ServerHandle = serverHandle,
|
|
||||||
ItemHandle = itemHandle,
|
|
||||||
UserId = arguments.GetInt32("user-id", 0),
|
|
||||||
Value = ParseValue(arguments),
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false));
|
|
||||||
}
|
|
||||||
|
|
||||||
using CancellationTokenSource streamCancellation = CancellationTokenSource
|
|
||||||
.CreateLinkedTokenSource(cancellationToken);
|
|
||||||
streamCancellation.CancelAfter(arguments.GetDuration(
|
|
||||||
"event-timeout",
|
|
||||||
TimeSpan.FromSeconds(2)));
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await foreach (MxEvent gatewayEvent in client.StreamEventsAsync(
|
|
||||||
new StreamEventsRequest { SessionId = openReply.SessionId },
|
|
||||||
streamCancellation.Token)
|
|
||||||
.WithCancellation(streamCancellation.Token)
|
|
||||||
.ConfigureAwait(false))
|
|
||||||
{
|
|
||||||
events.Add(gatewayEvent);
|
|
||||||
if (events.Count >= arguments.GetUInt32("max-events", 1))
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
if (openReply is not null)
|
|
||||||
{
|
|
||||||
closeReply = await client.CloseSessionAsync(
|
|
||||||
new CloseSessionRequest
|
|
||||||
{
|
|
||||||
SessionId = openReply.SessionId,
|
|
||||||
ClientCorrelationId = CreateCorrelationId(),
|
|
||||||
},
|
|
||||||
CancellationToken.None)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
WriteSmokeResult(arguments, output, openReply, closeReply, commandReplies, events);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<int> InvokeAndWriteAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
TextWriter output,
|
|
||||||
MxCommand command,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
MxCommandReply reply = await InvokeAndEnsureAsync(
|
|
||||||
client,
|
|
||||||
CreateCommandRequest(arguments.GetRequired("session-id"), command),
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
WriteMessage(arguments, output, reply);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<int> InvokeForHandleAsync(
|
|
||||||
CliArguments arguments,
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
string sessionId,
|
|
||||||
MxCommand command,
|
|
||||||
Func<MxCommandReply, int> handleSelector,
|
|
||||||
List<MxCommandReply> replies,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
MxCommandReply reply = await InvokeAndEnsureAsync(
|
|
||||||
client,
|
|
||||||
CreateCommandRequest(sessionId, command),
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
replies.Add(reply);
|
|
||||||
return handleSelector(reply);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<MxCommandReply> InvokeAndEnsureAsync(
|
|
||||||
IMxGatewayCliClient client,
|
|
||||||
MxCommandRequest request,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
MxCommandReply reply = await client.InvokeAsync(request, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
|
||||||
return reply;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static MxCommandRequest CreateCommandRequest(
|
|
||||||
string sessionId,
|
|
||||||
MxCommand command)
|
|
||||||
{
|
|
||||||
return new MxCommandRequest
|
|
||||||
{
|
|
||||||
SessionId = sessionId,
|
|
||||||
ClientCorrelationId = CreateCorrelationId(),
|
|
||||||
Command = command,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<int> WriteReplyAsync<TReply>(
|
|
||||||
Task<TReply> replyTask,
|
|
||||||
CliArguments arguments,
|
|
||||||
TextWriter output)
|
|
||||||
where TReply : IMessage
|
|
||||||
{
|
|
||||||
TReply reply = await replyTask.ConfigureAwait(false);
|
|
||||||
WriteMessage(arguments, output, reply);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void WriteVersion(CliArguments arguments, TextWriter output)
|
|
||||||
{
|
|
||||||
if (arguments.HasFlag("json"))
|
|
||||||
{
|
|
||||||
output.WriteLine(JsonSerializer.Serialize(
|
|
||||||
new
|
|
||||||
{
|
|
||||||
gatewayProtocolVersion = MxGatewayClientContractInfo.GatewayProtocolVersion,
|
|
||||||
workerProtocolVersion = MxGatewayClientContractInfo.WorkerProtocolVersion,
|
|
||||||
},
|
|
||||||
JsonOptions));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
output.WriteLine(
|
|
||||||
$"gateway-protocol={MxGatewayClientContractInfo.GatewayProtocolVersion}");
|
|
||||||
output.WriteLine(
|
|
||||||
$"worker-protocol={MxGatewayClientContractInfo.WorkerProtocolVersion}");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void WriteMessage(
|
|
||||||
CliArguments arguments,
|
|
||||||
TextWriter output,
|
|
||||||
IMessage message)
|
|
||||||
{
|
|
||||||
output.WriteLine(arguments.HasFlag("json")
|
|
||||||
? ProtobufJsonFormatter.Format(message)
|
|
||||||
: message.ToString());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void WriteSmokeResult(
|
|
||||||
CliArguments arguments,
|
|
||||||
TextWriter output,
|
|
||||||
OpenSessionReply? openReply,
|
|
||||||
CloseSessionReply? closeReply,
|
|
||||||
IReadOnlyList<MxCommandReply> commandReplies,
|
|
||||||
IReadOnlyList<MxEvent> events)
|
|
||||||
{
|
|
||||||
if (!arguments.HasFlag("json"))
|
|
||||||
{
|
|
||||||
output.WriteLine($"session-id={openReply?.SessionId}");
|
|
||||||
output.WriteLine($"commands={commandReplies.Count}");
|
|
||||||
output.WriteLine($"events={events.Count}");
|
|
||||||
output.WriteLine($"closed={closeReply is not null}");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
output.WriteLine(JsonSerializer.Serialize(
|
|
||||||
new
|
|
||||||
{
|
|
||||||
sessionId = openReply?.SessionId,
|
|
||||||
closed = closeReply is not null,
|
|
||||||
commandReplies = commandReplies.Select(CommandReplyToJsonElement).ToArray(),
|
|
||||||
events = events.Select(EventToJsonElement).ToArray(),
|
|
||||||
},
|
|
||||||
JsonOptions));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static JsonElement CommandReplyToJsonElement(MxCommandReply reply)
|
|
||||||
{
|
|
||||||
return JsonDocument.Parse(ProtobufJsonFormatter.Format(reply)).RootElement.Clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static JsonElement EventToJsonElement(MxEvent gatewayEvent)
|
|
||||||
{
|
|
||||||
return JsonDocument.Parse(ProtobufJsonFormatter.Format(gatewayEvent)).RootElement.Clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static MxValue ParseValue(CliArguments arguments)
|
|
||||||
{
|
|
||||||
string type = arguments.GetRequired("type").ToLowerInvariant();
|
|
||||||
string value = arguments.GetRequired("value");
|
|
||||||
string[] values = value.Split(',', StringSplitOptions.TrimEntries);
|
|
||||||
|
|
||||||
return type switch
|
|
||||||
{
|
|
||||||
"bool" or "boolean" => bool.Parse(value).ToMxValue(),
|
|
||||||
"bool-array" or "boolean-array" => values.Select(bool.Parse).ToArray().ToMxValue(),
|
|
||||||
"int32" or "integer" => int.Parse(value, CultureInfo.InvariantCulture).ToMxValue(),
|
|
||||||
"int32-array" or "integer-array" => values.Select(item => int.Parse(item, CultureInfo.InvariantCulture)).ToArray().ToMxValue(),
|
|
||||||
"int64" => long.Parse(value, CultureInfo.InvariantCulture).ToMxValue(),
|
|
||||||
"int64-array" => values.Select(item => long.Parse(item, CultureInfo.InvariantCulture)).ToArray().ToMxValue(),
|
|
||||||
"float" => float.Parse(value, CultureInfo.InvariantCulture).ToMxValue(),
|
|
||||||
"float-array" => values.Select(item => float.Parse(item, CultureInfo.InvariantCulture)).ToArray().ToMxValue(),
|
|
||||||
"double" => double.Parse(value, CultureInfo.InvariantCulture).ToMxValue(),
|
|
||||||
"double-array" => values.Select(item => double.Parse(item, CultureInfo.InvariantCulture)).ToArray().ToMxValue(),
|
|
||||||
"string" => value.ToMxValue(),
|
|
||||||
"string-array" => values.ToMxValue(),
|
|
||||||
"time" or "timestamp" => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToMxValue(),
|
|
||||||
"time-array" or "timestamp-array" => values
|
|
||||||
.Select(item => DateTimeOffset.Parse(item, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal))
|
|
||||||
.ToArray()
|
|
||||||
.ToMxValue(),
|
|
||||||
_ => throw new ArgumentException($"Unsupported MX value type '{type}'."),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private static MxValue ParseTimestampValue(CliArguments arguments)
|
|
||||||
{
|
|
||||||
string timestamp = arguments.GetOptional("timestamp")
|
|
||||||
?? DateTimeOffset.UtcNow.ToString("O", CultureInfo.InvariantCulture);
|
|
||||||
|
|
||||||
return DateTimeOffset.Parse(
|
|
||||||
timestamp,
|
|
||||||
CultureInfo.InvariantCulture,
|
|
||||||
DateTimeStyles.AssumeUniversal)
|
|
||||||
.ToMxValue();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int WriteUnknownCommand(string command, TextWriter standardError)
|
|
||||||
{
|
|
||||||
standardError.WriteLine($"Unknown command '{command}'.");
|
|
||||||
WriteUsage(standardError);
|
|
||||||
return 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsHelp(string value)
|
|
||||||
{
|
|
||||||
return string.Equals(value, "-h", StringComparison.OrdinalIgnoreCase)
|
|
||||||
|| string.Equals(value, "--help", StringComparison.OrdinalIgnoreCase)
|
|
||||||
|| string.Equals(value, "help", StringComparison.OrdinalIgnoreCase);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsKnownGatewayCommand(string command)
|
|
||||||
{
|
|
||||||
return command is "open-session"
|
|
||||||
or "close-session"
|
|
||||||
or "ping"
|
|
||||||
or "register"
|
|
||||||
or "add-item"
|
|
||||||
or "advise"
|
|
||||||
or "stream-events"
|
|
||||||
or "write"
|
|
||||||
or "write2"
|
|
||||||
or "smoke";
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string CreateCorrelationId()
|
|
||||||
{
|
|
||||||
return Guid.NewGuid().ToString("N");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void WriteUsage(TextWriter writer)
|
|
||||||
{
|
|
||||||
writer.WriteLine("mxgw-dotnet version [--json]");
|
|
||||||
writer.WriteLine("mxgw-dotnet ping --session-id <id> [--json]");
|
|
||||||
writer.WriteLine("mxgw-dotnet open-session [--client-name <name>] [--json]");
|
|
||||||
writer.WriteLine("mxgw-dotnet close-session --session-id <id> [--json]");
|
|
||||||
writer.WriteLine("mxgw-dotnet register --session-id <id> --client-name <name> [--json]");
|
|
||||||
writer.WriteLine("mxgw-dotnet add-item --session-id <id> --server-handle <n> --item <ref> [--json]");
|
|
||||||
writer.WriteLine("mxgw-dotnet advise --session-id <id> --server-handle <n> --item-handle <n> [--json]");
|
|
||||||
writer.WriteLine("mxgw-dotnet stream-events --session-id <id> [--max-events <n>] [--json]");
|
|
||||||
writer.WriteLine("mxgw-dotnet write --session-id <id> --server-handle <n> --item-handle <n> --type <type> --value <value> [--json]");
|
|
||||||
writer.WriteLine("mxgw-dotnet write2 --session-id <id> --server-handle <n> --item-handle <n> --type <type> --value <value> [--timestamp <iso>] [--json]");
|
|
||||||
writer.WriteLine("mxgw-dotnet smoke --item <ref> [--value <value> --type <type>] [--json]");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
using Grpc.Core;
|
|
||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client.Tests;
|
|
||||||
|
|
||||||
internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMxGatewayClientTransport
|
|
||||||
{
|
|
||||||
private readonly Queue<MxCommandReply> _invokeReplies = new();
|
|
||||||
private readonly List<MxEvent> _events = [];
|
|
||||||
|
|
||||||
public MxGatewayClientOptions Options { get; } = options;
|
|
||||||
|
|
||||||
public MxAccessGateway.MxAccessGatewayClient? RawClient => null;
|
|
||||||
|
|
||||||
public List<(OpenSessionRequest Request, CallOptions CallOptions)> OpenSessionCalls { get; } = [];
|
|
||||||
|
|
||||||
public List<(CloseSessionRequest Request, CallOptions CallOptions)> CloseSessionCalls { get; } = [];
|
|
||||||
|
|
||||||
public List<(MxCommandRequest Request, CallOptions CallOptions)> InvokeCalls { get; } = [];
|
|
||||||
|
|
||||||
public List<(StreamEventsRequest Request, CallOptions CallOptions)> StreamEventsCalls { get; } = [];
|
|
||||||
|
|
||||||
public OpenSessionReply OpenSessionReply { get; set; } = new()
|
|
||||||
{
|
|
||||||
SessionId = "session-fixture",
|
|
||||||
BackendName = "mxaccess-worker",
|
|
||||||
GatewayProtocolVersion = 1,
|
|
||||||
WorkerProtocolVersion = 1,
|
|
||||||
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
|
||||||
};
|
|
||||||
|
|
||||||
public CloseSessionReply CloseSessionReply { get; set; } = new()
|
|
||||||
{
|
|
||||||
SessionId = "session-fixture",
|
|
||||||
FinalState = SessionState.Closed,
|
|
||||||
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
|
||||||
};
|
|
||||||
|
|
||||||
public Task<OpenSessionReply> OpenSessionAsync(
|
|
||||||
OpenSessionRequest request,
|
|
||||||
CallOptions callOptions)
|
|
||||||
{
|
|
||||||
OpenSessionCalls.Add((request, callOptions));
|
|
||||||
return Task.FromResult(OpenSessionReply);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<CloseSessionReply> CloseSessionAsync(
|
|
||||||
CloseSessionRequest request,
|
|
||||||
CallOptions callOptions)
|
|
||||||
{
|
|
||||||
CloseSessionCalls.Add((request, callOptions));
|
|
||||||
return Task.FromResult(CloseSessionReply);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> InvokeAsync(
|
|
||||||
MxCommandRequest request,
|
|
||||||
CallOptions callOptions)
|
|
||||||
{
|
|
||||||
InvokeCalls.Add((request, callOptions));
|
|
||||||
return Task.FromResult(_invokeReplies.Dequeue());
|
|
||||||
}
|
|
||||||
|
|
||||||
public async IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
|
||||||
StreamEventsRequest request,
|
|
||||||
CallOptions callOptions)
|
|
||||||
{
|
|
||||||
StreamEventsCalls.Add((request, callOptions));
|
|
||||||
|
|
||||||
foreach (MxEvent gatewayEvent in _events)
|
|
||||||
{
|
|
||||||
callOptions.CancellationToken.ThrowIfCancellationRequested();
|
|
||||||
await Task.Yield();
|
|
||||||
yield return gatewayEvent;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void AddInvokeReply(MxCommandReply reply)
|
|
||||||
{
|
|
||||||
_invokeReplies.Enqueue(reply);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void AddEvent(MxEvent gatewayEvent)
|
|
||||||
{
|
|
||||||
_events.Add(gatewayEvent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,241 +0,0 @@
|
|||||||
using MxGateway.Client.Cli;
|
|
||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client.Tests;
|
|
||||||
|
|
||||||
public sealed class MxGatewayClientCliTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public void Run_Version_PrintsCompiledProtocolVersions()
|
|
||||||
{
|
|
||||||
using var output = new StringWriter();
|
|
||||||
using var error = new StringWriter();
|
|
||||||
|
|
||||||
var exitCode = MxGatewayClientCli.Run(["version"], output, error);
|
|
||||||
|
|
||||||
Assert.Equal(0, exitCode);
|
|
||||||
Assert.Contains("gateway-protocol=1", output.ToString());
|
|
||||||
Assert.Contains("worker-protocol=1", output.ToString());
|
|
||||||
Assert.Equal(string.Empty, error.ToString());
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task RunAsync_VersionJson_PrintsJsonProtocolVersions()
|
|
||||||
{
|
|
||||||
using var output = new StringWriter();
|
|
||||||
using var error = new StringWriter();
|
|
||||||
|
|
||||||
int exitCode = await MxGatewayClientCli.RunAsync(["version", "--json"], output, error);
|
|
||||||
|
|
||||||
Assert.Equal(0, exitCode);
|
|
||||||
Assert.Contains("\"gatewayProtocolVersion\":1", output.ToString());
|
|
||||||
Assert.Equal(string.Empty, error.ToString());
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task RunAsync_Write_BuildsWriteCommandAndPrintsJsonReply()
|
|
||||||
{
|
|
||||||
using var output = new StringWriter();
|
|
||||||
using var error = new StringWriter();
|
|
||||||
FakeCliClient fakeClient = new();
|
|
||||||
fakeClient.InvokeReplies.Enqueue(new MxCommandReply
|
|
||||||
{
|
|
||||||
SessionId = "session-fixture",
|
|
||||||
Kind = MxCommandKind.Write,
|
|
||||||
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
|
||||||
});
|
|
||||||
|
|
||||||
int exitCode = await MxGatewayClientCli.RunAsync(
|
|
||||||
[
|
|
||||||
"write",
|
|
||||||
"--endpoint",
|
|
||||||
"http://localhost:5000",
|
|
||||||
"--api-key",
|
|
||||||
"test-api-key",
|
|
||||||
"--session-id",
|
|
||||||
"session-fixture",
|
|
||||||
"--server-handle",
|
|
||||||
"12",
|
|
||||||
"--item-handle",
|
|
||||||
"34",
|
|
||||||
"--type",
|
|
||||||
"int32",
|
|
||||||
"--value",
|
|
||||||
"123",
|
|
||||||
"--json",
|
|
||||||
],
|
|
||||||
output,
|
|
||||||
error,
|
|
||||||
_ => fakeClient);
|
|
||||||
|
|
||||||
Assert.Equal(0, exitCode);
|
|
||||||
MxCommandRequest request = Assert.Single(fakeClient.InvokeRequests);
|
|
||||||
Assert.Equal(MxCommandKind.Write, request.Command.Kind);
|
|
||||||
Assert.Equal(123, request.Command.Write.Value.Int32Value);
|
|
||||||
Assert.Contains("MX_COMMAND_KIND_WRITE", output.ToString());
|
|
||||||
Assert.Equal(string.Empty, error.ToString());
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task RunAsync_ErrorOutput_RedactsApiKey()
|
|
||||||
{
|
|
||||||
using var output = new StringWriter();
|
|
||||||
using var error = new StringWriter();
|
|
||||||
|
|
||||||
int exitCode = await MxGatewayClientCli.RunAsync(
|
|
||||||
[
|
|
||||||
"open-session",
|
|
||||||
"--endpoint",
|
|
||||||
"http://localhost:5000",
|
|
||||||
"--api-key",
|
|
||||||
"secret-api-key",
|
|
||||||
],
|
|
||||||
output,
|
|
||||||
error,
|
|
||||||
_ => throw new InvalidOperationException("boom secret-api-key"));
|
|
||||||
|
|
||||||
Assert.Equal(1, exitCode);
|
|
||||||
Assert.DoesNotContain("secret-api-key", error.ToString());
|
|
||||||
Assert.Contains("[redacted]", error.ToString());
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task RunAsync_StreamEvents_WithMaxEventsStopsNonJsonOutput()
|
|
||||||
{
|
|
||||||
using var output = new StringWriter();
|
|
||||||
using var error = new StringWriter();
|
|
||||||
FakeCliClient fakeClient = new();
|
|
||||||
fakeClient.Events.Add(new MxEvent
|
|
||||||
{
|
|
||||||
SessionId = "session-fixture",
|
|
||||||
Family = MxEventFamily.OnDataChange,
|
|
||||||
WorkerSequence = 1,
|
|
||||||
});
|
|
||||||
fakeClient.Events.Add(new MxEvent
|
|
||||||
{
|
|
||||||
SessionId = "session-fixture",
|
|
||||||
Family = MxEventFamily.OnWriteComplete,
|
|
||||||
WorkerSequence = 2,
|
|
||||||
});
|
|
||||||
|
|
||||||
int exitCode = await MxGatewayClientCli.RunAsync(
|
|
||||||
[
|
|
||||||
"stream-events",
|
|
||||||
"--endpoint",
|
|
||||||
"http://localhost:5000",
|
|
||||||
"--api-key",
|
|
||||||
"test-api-key",
|
|
||||||
"--session-id",
|
|
||||||
"session-fixture",
|
|
||||||
"--max-events",
|
|
||||||
"1",
|
|
||||||
],
|
|
||||||
output,
|
|
||||||
error,
|
|
||||||
_ => fakeClient);
|
|
||||||
|
|
||||||
Assert.Equal(0, exitCode);
|
|
||||||
Assert.Contains("workerSequence", output.ToString());
|
|
||||||
Assert.DoesNotContain("ON_WRITE_COMPLETE", output.ToString());
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task RunAsync_Smoke_WhenCommandFails_ClosesOpenedSession()
|
|
||||||
{
|
|
||||||
using var output = new StringWriter();
|
|
||||||
using var error = new StringWriter();
|
|
||||||
FakeCliClient fakeClient = new()
|
|
||||||
{
|
|
||||||
InvokeFailure = new InvalidOperationException("register failed"),
|
|
||||||
};
|
|
||||||
|
|
||||||
int exitCode = await MxGatewayClientCli.RunAsync(
|
|
||||||
[
|
|
||||||
"smoke",
|
|
||||||
"--endpoint",
|
|
||||||
"http://localhost:5000",
|
|
||||||
"--api-key",
|
|
||||||
"test-api-key",
|
|
||||||
"--item",
|
|
||||||
"Area001.Pump001.Speed",
|
|
||||||
"--json",
|
|
||||||
],
|
|
||||||
output,
|
|
||||||
error,
|
|
||||||
_ => fakeClient);
|
|
||||||
|
|
||||||
Assert.Equal(1, exitCode);
|
|
||||||
CloseSessionRequest closeRequest = Assert.Single(fakeClient.CloseSessionRequests);
|
|
||||||
Assert.Equal("session-fixture", closeRequest.SessionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class FakeCliClient : IMxGatewayCliClient
|
|
||||||
{
|
|
||||||
public Queue<MxCommandReply> InvokeReplies { get; } = new();
|
|
||||||
|
|
||||||
public List<MxCommandRequest> InvokeRequests { get; } = [];
|
|
||||||
|
|
||||||
public List<CloseSessionRequest> CloseSessionRequests { get; } = [];
|
|
||||||
|
|
||||||
public List<MxEvent> Events { get; } = [];
|
|
||||||
|
|
||||||
public Exception? InvokeFailure { get; init; }
|
|
||||||
|
|
||||||
public ValueTask DisposeAsync()
|
|
||||||
{
|
|
||||||
return ValueTask.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<OpenSessionReply> OpenSessionAsync(
|
|
||||||
OpenSessionRequest request,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return Task.FromResult(new OpenSessionReply
|
|
||||||
{
|
|
||||||
SessionId = "session-fixture",
|
|
||||||
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
|
||||||
GatewayProtocolVersion = 1,
|
|
||||||
WorkerProtocolVersion = 1,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<CloseSessionReply> CloseSessionAsync(
|
|
||||||
CloseSessionRequest request,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
CloseSessionRequests.Add(request);
|
|
||||||
return Task.FromResult(new CloseSessionReply
|
|
||||||
{
|
|
||||||
SessionId = request.SessionId,
|
|
||||||
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
|
||||||
FinalState = SessionState.Closed,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> InvokeAsync(
|
|
||||||
MxCommandRequest request,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
InvokeRequests.Add(request);
|
|
||||||
if (InvokeFailure is not null)
|
|
||||||
{
|
|
||||||
throw InvokeFailure;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Task.FromResult(InvokeReplies.Dequeue());
|
|
||||||
}
|
|
||||||
|
|
||||||
public async IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
|
||||||
StreamEventsRequest request,
|
|
||||||
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
foreach (MxEvent gatewayEvent in Events)
|
|
||||||
{
|
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
|
||||||
await Task.Yield();
|
|
||||||
yield return gatewayEvent;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
namespace MxGateway.Client.Tests;
|
|
||||||
|
|
||||||
public sealed class MxGatewayClientOptionsTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public void Validate_WithAbsoluteEndpointAndApiKey_Succeeds()
|
|
||||||
{
|
|
||||||
var options = new MxGatewayClientOptions
|
|
||||||
{
|
|
||||||
Endpoint = new Uri("http://localhost:5000"),
|
|
||||||
ApiKey = "test-api-key",
|
|
||||||
};
|
|
||||||
|
|
||||||
options.Validate();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Validate_WithEmptyApiKey_Throws()
|
|
||||||
{
|
|
||||||
var options = new MxGatewayClientOptions
|
|
||||||
{
|
|
||||||
Endpoint = new Uri("http://localhost:5000"),
|
|
||||||
ApiKey = "",
|
|
||||||
};
|
|
||||||
|
|
||||||
Assert.Throws<ArgumentException>(options.Validate);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
|
||||||
# Visual Studio Version 17
|
|
||||||
VisualStudioVersion = 17.0.31903.59
|
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MxGateway.Client", "MxGateway.Client\MxGateway.Client.csproj", "{7CF9ED88-1F32-4040-BEB1-D0902E304C70}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MxGateway.Contracts", "..\..\src\MxGateway.Contracts\MxGateway.Contracts.csproj", "{9AB807A8-0469-40F7-A000-D240F36B6E5D}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MxGateway.Client.Cli", "MxGateway.Client.Cli\MxGateway.Client.Cli.csproj", "{EB061E77-2475-4322-9257-3F2456DD141C}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MxGateway.Client.Tests", "MxGateway.Client.Tests\MxGateway.Client.Tests.csproj", "{B77B5A8E-0C53-4419-9BCD-227C9753A074}"
|
|
||||||
EndProject
|
|
||||||
Global
|
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
|
||||||
Debug|Any CPU = Debug|Any CPU
|
|
||||||
Debug|x64 = Debug|x64
|
|
||||||
Debug|x86 = Debug|x86
|
|
||||||
Release|Any CPU = Release|Any CPU
|
|
||||||
Release|x64 = Release|x64
|
|
||||||
Release|x86 = Release|x86
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Debug|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Debug|x64.Build.0 = Debug|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Debug|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Debug|x86.Build.0 = Debug|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Release|x64.ActiveCfg = Release|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Release|x64.Build.0 = Release|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Release|x86.ActiveCfg = Release|Any CPU
|
|
||||||
{7CF9ED88-1F32-4040-BEB1-D0902E304C70}.Release|x86.Build.0 = Release|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Debug|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Debug|x64.Build.0 = Debug|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Debug|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Debug|x86.Build.0 = Debug|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Release|x64.ActiveCfg = Release|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Release|x64.Build.0 = Release|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Release|x86.ActiveCfg = Release|Any CPU
|
|
||||||
{9AB807A8-0469-40F7-A000-D240F36B6E5D}.Release|x86.Build.0 = Release|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Debug|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Debug|x64.Build.0 = Debug|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Debug|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Debug|x86.Build.0 = Debug|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Release|x64.ActiveCfg = Release|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Release|x64.Build.0 = Release|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Release|x86.ActiveCfg = Release|Any CPU
|
|
||||||
{EB061E77-2475-4322-9257-3F2456DD141C}.Release|x86.Build.0 = Release|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Debug|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Debug|x64.Build.0 = Debug|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Debug|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Debug|x86.Build.0 = Debug|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Release|x64.ActiveCfg = Release|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Release|x64.Build.0 = Release|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Release|x86.ActiveCfg = Release|Any CPU
|
|
||||||
{B77B5A8E-0C53-4419-9BCD-227C9753A074}.Release|x86.Build.0 = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
|
||||||
HideSolutionNode = FALSE
|
|
||||||
EndGlobalSection
|
|
||||||
EndGlobal
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
using Grpc.Core;
|
|
||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
internal sealed class GrpcMxGatewayClientTransport(
|
|
||||||
MxGatewayClientOptions options,
|
|
||||||
MxAccessGateway.MxAccessGatewayClient rawClient) : IMxGatewayClientTransport
|
|
||||||
{
|
|
||||||
public MxGatewayClientOptions Options { get; } = options;
|
|
||||||
|
|
||||||
public MxAccessGateway.MxAccessGatewayClient RawClient { get; } = rawClient;
|
|
||||||
|
|
||||||
MxAccessGateway.MxAccessGatewayClient? IMxGatewayClientTransport.RawClient => RawClient;
|
|
||||||
|
|
||||||
public async Task<OpenSessionReply> OpenSessionAsync(
|
|
||||||
OpenSessionRequest request,
|
|
||||||
CallOptions callOptions)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return await RawClient.OpenSessionAsync(request, callOptions)
|
|
||||||
.ResponseAsync
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (RpcException exception)
|
|
||||||
{
|
|
||||||
throw MapRpcException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<CloseSessionReply> CloseSessionAsync(
|
|
||||||
CloseSessionRequest request,
|
|
||||||
CallOptions callOptions)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return await RawClient.CloseSessionAsync(request, callOptions)
|
|
||||||
.ResponseAsync
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (RpcException exception)
|
|
||||||
{
|
|
||||||
throw MapRpcException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<MxCommandReply> InvokeAsync(
|
|
||||||
MxCommandRequest request,
|
|
||||||
CallOptions callOptions)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return await RawClient.InvokeAsync(request, callOptions)
|
|
||||||
.ResponseAsync
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (RpcException exception)
|
|
||||||
{
|
|
||||||
throw MapRpcException(exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
|
||||||
StreamEventsRequest request,
|
|
||||||
CallOptions callOptions,
|
|
||||||
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
CancellationToken effectiveCancellationToken = cancellationToken.CanBeCanceled
|
|
||||||
? cancellationToken
|
|
||||||
: callOptions.CancellationToken;
|
|
||||||
|
|
||||||
using AsyncServerStreamingCall<MxEvent> call = RawClient.StreamEvents(request, callOptions);
|
|
||||||
|
|
||||||
IAsyncStreamReader<MxEvent> responseStream = call.ResponseStream;
|
|
||||||
while (true)
|
|
||||||
{
|
|
||||||
MxEvent? gatewayEvent;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (!await responseStream.MoveNext(effectiveCancellationToken).ConfigureAwait(false))
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
gatewayEvent = responseStream.Current;
|
|
||||||
}
|
|
||||||
catch (RpcException exception)
|
|
||||||
{
|
|
||||||
throw MapRpcException(exception);
|
|
||||||
}
|
|
||||||
|
|
||||||
yield return gatewayEvent;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
IAsyncEnumerable<MxEvent> IMxGatewayClientTransport.StreamEventsAsync(
|
|
||||||
StreamEventsRequest request,
|
|
||||||
CallOptions callOptions)
|
|
||||||
{
|
|
||||||
return StreamEventsAsync(request, callOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static MxGatewayException MapRpcException(RpcException exception)
|
|
||||||
{
|
|
||||||
return exception.StatusCode switch
|
|
||||||
{
|
|
||||||
StatusCode.Unauthenticated => new MxGatewayAuthenticationException(
|
|
||||||
exception.Status.Detail,
|
|
||||||
innerException: exception),
|
|
||||||
StatusCode.PermissionDenied => new MxGatewayAuthorizationException(
|
|
||||||
exception.Status.Detail,
|
|
||||||
innerException: exception),
|
|
||||||
_ => new MxGatewayException(exception.Status.Detail, exception),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
using Grpc.Core;
|
|
||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
internal interface IMxGatewayClientTransport
|
|
||||||
{
|
|
||||||
MxGatewayClientOptions Options { get; }
|
|
||||||
|
|
||||||
MxAccessGateway.MxAccessGatewayClient? RawClient { get; }
|
|
||||||
|
|
||||||
Task<OpenSessionReply> OpenSessionAsync(
|
|
||||||
OpenSessionRequest request,
|
|
||||||
CallOptions callOptions);
|
|
||||||
|
|
||||||
Task<CloseSessionReply> CloseSessionAsync(
|
|
||||||
CloseSessionRequest request,
|
|
||||||
CallOptions callOptions);
|
|
||||||
|
|
||||||
Task<MxCommandReply> InvokeAsync(
|
|
||||||
MxCommandRequest request,
|
|
||||||
CallOptions callOptions);
|
|
||||||
|
|
||||||
IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
|
||||||
StreamEventsRequest request,
|
|
||||||
CallOptions callOptions);
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
public sealed class MxAccessException : MxGatewayCommandException
|
|
||||||
{
|
|
||||||
public MxAccessException(
|
|
||||||
string message,
|
|
||||||
MxCommandReply reply,
|
|
||||||
Exception? innerException = null)
|
|
||||||
: base(
|
|
||||||
message,
|
|
||||||
reply.SessionId,
|
|
||||||
reply.CorrelationId,
|
|
||||||
reply.ProtocolStatus,
|
|
||||||
reply.HasHresult ? reply.Hresult : null,
|
|
||||||
reply.Statuses.ToArray(),
|
|
||||||
innerException)
|
|
||||||
{
|
|
||||||
Reply = reply;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MxCommandReply Reply { get; }
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\..\..\src\MxGateway.Contracts\MxGateway.Contracts.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="Grpc.Net.Client" Version="2.76.0" />
|
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.7" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
public sealed class MxGatewayAuthenticationException : MxGatewayException
|
|
||||||
{
|
|
||||||
public MxGatewayAuthenticationException(
|
|
||||||
string message,
|
|
||||||
string? sessionId = null,
|
|
||||||
string? correlationId = null,
|
|
||||||
ProtocolStatus? protocolStatus = null,
|
|
||||||
int? hResult = null,
|
|
||||||
IReadOnlyList<MxStatusProxy>? statuses = null,
|
|
||||||
Exception? innerException = null)
|
|
||||||
: base(
|
|
||||||
message,
|
|
||||||
sessionId,
|
|
||||||
correlationId,
|
|
||||||
protocolStatus,
|
|
||||||
hResult,
|
|
||||||
statuses ?? [],
|
|
||||||
innerException)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
public sealed class MxGatewayAuthorizationException : MxGatewayException
|
|
||||||
{
|
|
||||||
public MxGatewayAuthorizationException(
|
|
||||||
string message,
|
|
||||||
string? sessionId = null,
|
|
||||||
string? correlationId = null,
|
|
||||||
ProtocolStatus? protocolStatus = null,
|
|
||||||
int? hResult = null,
|
|
||||||
IReadOnlyList<MxStatusProxy>? statuses = null,
|
|
||||||
Exception? innerException = null)
|
|
||||||
: base(
|
|
||||||
message,
|
|
||||||
sessionId,
|
|
||||||
correlationId,
|
|
||||||
protocolStatus,
|
|
||||||
hResult,
|
|
||||||
statuses ?? [],
|
|
||||||
innerException)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,143 +0,0 @@
|
|||||||
using Grpc.Core;
|
|
||||||
using Grpc.Net.Client;
|
|
||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Provides the .NET client entry point for the public MXAccess Gateway gRPC API.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class MxGatewayClient : IAsyncDisposable
|
|
||||||
{
|
|
||||||
private readonly GrpcChannel _channel;
|
|
||||||
private readonly IMxGatewayClientTransport _transport;
|
|
||||||
private bool _disposed;
|
|
||||||
|
|
||||||
internal MxGatewayClient(
|
|
||||||
MxGatewayClientOptions options,
|
|
||||||
IMxGatewayClientTransport transport)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(options);
|
|
||||||
options.Validate();
|
|
||||||
|
|
||||||
Options = options;
|
|
||||||
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
|
||||||
_channel = null!;
|
|
||||||
}
|
|
||||||
|
|
||||||
private MxGatewayClient(
|
|
||||||
GrpcChannel channel,
|
|
||||||
IMxGatewayClientTransport transport)
|
|
||||||
{
|
|
||||||
_channel = channel;
|
|
||||||
_transport = transport;
|
|
||||||
Options = transport.Options;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MxGatewayClientOptions Options { get; }
|
|
||||||
|
|
||||||
public MxAccessGateway.MxAccessGatewayClient RawClient =>
|
|
||||||
_transport.RawClient
|
|
||||||
?? throw new InvalidOperationException("The raw generated gRPC client is not available for this client instance.");
|
|
||||||
|
|
||||||
public static MxGatewayClient Create(MxGatewayClientOptions options)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(options);
|
|
||||||
options.Validate();
|
|
||||||
|
|
||||||
var channel = GrpcChannel.ForAddress(
|
|
||||||
options.Endpoint,
|
|
||||||
new GrpcChannelOptions
|
|
||||||
{
|
|
||||||
LoggerFactory = options.LoggerFactory,
|
|
||||||
});
|
|
||||||
|
|
||||||
return new MxGatewayClient(
|
|
||||||
channel,
|
|
||||||
new GrpcMxGatewayClientTransport(
|
|
||||||
options,
|
|
||||||
new MxAccessGateway.MxAccessGatewayClient(channel)));
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<MxGatewaySession> OpenSessionAsync(
|
|
||||||
OpenSessionRequest? request = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
OpenSessionReply reply = await OpenSessionRawAsync(
|
|
||||||
request ?? new OpenSessionRequest(),
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
return new MxGatewaySession(this, reply);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<OpenSessionReply> OpenSessionRawAsync(
|
|
||||||
OpenSessionRequest request,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(request);
|
|
||||||
ThrowIfDisposed();
|
|
||||||
|
|
||||||
return _transport.OpenSessionAsync(request, CreateCallOptions(cancellationToken));
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<CloseSessionReply> CloseSessionRawAsync(
|
|
||||||
CloseSessionRequest request,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(request);
|
|
||||||
ThrowIfDisposed();
|
|
||||||
|
|
||||||
return _transport.CloseSessionAsync(request, CreateCallOptions(cancellationToken));
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> InvokeAsync(
|
|
||||||
MxCommandRequest request,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(request);
|
|
||||||
ThrowIfDisposed();
|
|
||||||
|
|
||||||
return _transport.InvokeAsync(request, CreateCallOptions(cancellationToken));
|
|
||||||
}
|
|
||||||
|
|
||||||
public IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
|
||||||
StreamEventsRequest request,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(request);
|
|
||||||
ThrowIfDisposed();
|
|
||||||
|
|
||||||
return _transport.StreamEventsAsync(request, CreateCallOptions(cancellationToken));
|
|
||||||
}
|
|
||||||
|
|
||||||
public ValueTask DisposeAsync()
|
|
||||||
{
|
|
||||||
if (_disposed)
|
|
||||||
{
|
|
||||||
return ValueTask.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
_disposed = true;
|
|
||||||
_channel?.Dispose();
|
|
||||||
return ValueTask.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal CallOptions CreateCallOptions(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
Metadata headers = new()
|
|
||||||
{
|
|
||||||
{ "authorization", $"Bearer {Options.ApiKey}" },
|
|
||||||
};
|
|
||||||
|
|
||||||
return new CallOptions(
|
|
||||||
headers,
|
|
||||||
DateTime.UtcNow.Add(Options.DefaultCallTimeout),
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ThrowIfDisposed()
|
|
||||||
{
|
|
||||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
using Microsoft.Extensions.Logging;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Configures the gRPC channel used by the .NET MXAccess Gateway client.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class MxGatewayClientOptions
|
|
||||||
{
|
|
||||||
public required Uri Endpoint { get; init; }
|
|
||||||
|
|
||||||
public required string ApiKey { get; init; }
|
|
||||||
|
|
||||||
public bool UseTls { get; init; }
|
|
||||||
|
|
||||||
public string? CaCertificatePath { get; init; }
|
|
||||||
|
|
||||||
public string? ServerNameOverride { get; init; }
|
|
||||||
|
|
||||||
public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10);
|
|
||||||
|
|
||||||
public TimeSpan DefaultCallTimeout { get; init; } = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
public ILoggerFactory? LoggerFactory { get; init; }
|
|
||||||
|
|
||||||
public void Validate()
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(Endpoint);
|
|
||||||
|
|
||||||
if (!Endpoint.IsAbsoluteUri)
|
|
||||||
{
|
|
||||||
throw new ArgumentException(
|
|
||||||
"The gateway endpoint must be an absolute URI.",
|
|
||||||
nameof(Endpoint));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(ApiKey))
|
|
||||||
{
|
|
||||||
throw new ArgumentException(
|
|
||||||
"The gateway API key must not be empty.",
|
|
||||||
nameof(ApiKey));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ConnectTimeout <= TimeSpan.Zero)
|
|
||||||
{
|
|
||||||
throw new ArgumentOutOfRangeException(
|
|
||||||
nameof(ConnectTimeout),
|
|
||||||
"The connect timeout must be greater than zero.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (DefaultCallTimeout <= TimeSpan.Zero)
|
|
||||||
{
|
|
||||||
throw new ArgumentOutOfRangeException(
|
|
||||||
nameof(DefaultCallTimeout),
|
|
||||||
"The default call timeout must be greater than zero.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
public class MxGatewayCommandException : MxGatewayException
|
|
||||||
{
|
|
||||||
public MxGatewayCommandException(
|
|
||||||
string message,
|
|
||||||
string? sessionId = null,
|
|
||||||
string? correlationId = null,
|
|
||||||
ProtocolStatus? protocolStatus = null,
|
|
||||||
int? hResult = null,
|
|
||||||
IReadOnlyList<MxStatusProxy>? statuses = null,
|
|
||||||
Exception? innerException = null)
|
|
||||||
: base(
|
|
||||||
message,
|
|
||||||
sessionId,
|
|
||||||
correlationId,
|
|
||||||
protocolStatus,
|
|
||||||
hResult,
|
|
||||||
statuses ?? [],
|
|
||||||
innerException)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
public class MxGatewayException : Exception
|
|
||||||
{
|
|
||||||
public MxGatewayException(string message)
|
|
||||||
: base(message)
|
|
||||||
{
|
|
||||||
Statuses = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
public MxGatewayException(string message, Exception? innerException)
|
|
||||||
: base(message, innerException)
|
|
||||||
{
|
|
||||||
Statuses = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
public MxGatewayException(
|
|
||||||
string message,
|
|
||||||
string? sessionId,
|
|
||||||
string? correlationId,
|
|
||||||
ProtocolStatus? protocolStatus,
|
|
||||||
int? hResult,
|
|
||||||
IReadOnlyList<MxStatusProxy> statuses,
|
|
||||||
Exception? innerException = null)
|
|
||||||
: base(message, innerException)
|
|
||||||
{
|
|
||||||
SessionId = sessionId;
|
|
||||||
CorrelationId = correlationId;
|
|
||||||
ProtocolStatus = protocolStatus;
|
|
||||||
HResultCode = hResult;
|
|
||||||
Statuses = statuses;
|
|
||||||
}
|
|
||||||
|
|
||||||
public string? SessionId { get; }
|
|
||||||
|
|
||||||
public string? CorrelationId { get; }
|
|
||||||
|
|
||||||
public ProtocolStatus? ProtocolStatus { get; }
|
|
||||||
|
|
||||||
public int? HResultCode { get; }
|
|
||||||
|
|
||||||
public IReadOnlyList<MxStatusProxy> Statuses { get; }
|
|
||||||
}
|
|
||||||
@@ -1,300 +0,0 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Represents one gateway-backed MXAccess session.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class MxGatewaySession : IAsyncDisposable
|
|
||||||
{
|
|
||||||
private readonly MxGatewayClient _client;
|
|
||||||
private readonly SemaphoreSlim _closeLock = new(1, 1);
|
|
||||||
private CloseSessionReply? _closeReply;
|
|
||||||
|
|
||||||
internal MxGatewaySession(
|
|
||||||
MxGatewayClient client,
|
|
||||||
OpenSessionReply openSessionReply)
|
|
||||||
{
|
|
||||||
_client = client ?? throw new ArgumentNullException(nameof(client));
|
|
||||||
OpenSessionReply = openSessionReply ?? throw new ArgumentNullException(nameof(openSessionReply));
|
|
||||||
}
|
|
||||||
|
|
||||||
public string SessionId => OpenSessionReply.SessionId;
|
|
||||||
|
|
||||||
public OpenSessionReply OpenSessionReply { get; }
|
|
||||||
|
|
||||||
public async Task<CloseSessionReply> CloseAsync(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
if (_closeReply is not null)
|
|
||||||
{
|
|
||||||
return _closeReply;
|
|
||||||
}
|
|
||||||
|
|
||||||
await _closeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (_closeReply is not null)
|
|
||||||
{
|
|
||||||
return _closeReply;
|
|
||||||
}
|
|
||||||
|
|
||||||
_closeReply = await _client.CloseSessionRawAsync(
|
|
||||||
new CloseSessionRequest { SessionId = SessionId },
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
return _closeReply;
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_closeLock.Release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<int> RegisterAsync(
|
|
||||||
string clientName,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
MxCommandReply reply = await RegisterRawAsync(clientName, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
|
||||||
return reply.Register?.ServerHandle ?? reply.ReturnValue.Int32Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> RegisterRawAsync(
|
|
||||||
string clientName,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(clientName);
|
|
||||||
|
|
||||||
return InvokeCommandAsync(
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Register,
|
|
||||||
Register = new RegisterCommand { ClientName = clientName },
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<int> AddItemAsync(
|
|
||||||
int serverHandle,
|
|
||||||
string itemDefinition,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
MxCommandReply reply = await AddItemRawAsync(
|
|
||||||
serverHandle,
|
|
||||||
itemDefinition,
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
|
||||||
return reply.AddItem?.ItemHandle ?? reply.ReturnValue.Int32Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> AddItemRawAsync(
|
|
||||||
int serverHandle,
|
|
||||||
string itemDefinition,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(itemDefinition);
|
|
||||||
|
|
||||||
return InvokeCommandAsync(
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.AddItem,
|
|
||||||
AddItem = new AddItemCommand
|
|
||||||
{
|
|
||||||
ServerHandle = serverHandle,
|
|
||||||
ItemDefinition = itemDefinition,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<int> AddItem2Async(
|
|
||||||
int serverHandle,
|
|
||||||
string itemDefinition,
|
|
||||||
string itemContext,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
MxCommandReply reply = await AddItem2RawAsync(
|
|
||||||
serverHandle,
|
|
||||||
itemDefinition,
|
|
||||||
itemContext,
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
|
||||||
return reply.AddItem2?.ItemHandle ?? reply.ReturnValue.Int32Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> AddItem2RawAsync(
|
|
||||||
int serverHandle,
|
|
||||||
string itemDefinition,
|
|
||||||
string itemContext,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(itemDefinition);
|
|
||||||
|
|
||||||
return InvokeCommandAsync(
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.AddItem2,
|
|
||||||
AddItem2 = new AddItem2Command
|
|
||||||
{
|
|
||||||
ServerHandle = serverHandle,
|
|
||||||
ItemDefinition = itemDefinition,
|
|
||||||
ItemContext = itemContext ?? string.Empty,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task AdviseAsync(
|
|
||||||
int serverHandle,
|
|
||||||
int itemHandle,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
MxCommandReply reply = await AdviseRawAsync(serverHandle, itemHandle, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> AdviseRawAsync(
|
|
||||||
int serverHandle,
|
|
||||||
int itemHandle,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
return InvokeCommandAsync(
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Advise,
|
|
||||||
Advise = new AdviseCommand
|
|
||||||
{
|
|
||||||
ServerHandle = serverHandle,
|
|
||||||
ItemHandle = itemHandle,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task WriteAsync(
|
|
||||||
int serverHandle,
|
|
||||||
int itemHandle,
|
|
||||||
MxValue value,
|
|
||||||
int userId,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
MxCommandReply reply = await WriteRawAsync(serverHandle, itemHandle, value, userId, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> WriteRawAsync(
|
|
||||||
int serverHandle,
|
|
||||||
int itemHandle,
|
|
||||||
MxValue value,
|
|
||||||
int userId,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(value);
|
|
||||||
|
|
||||||
return InvokeCommandAsync(
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Write,
|
|
||||||
Write = new WriteCommand
|
|
||||||
{
|
|
||||||
ServerHandle = serverHandle,
|
|
||||||
ItemHandle = itemHandle,
|
|
||||||
Value = value,
|
|
||||||
UserId = userId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Write2Async(
|
|
||||||
int serverHandle,
|
|
||||||
int itemHandle,
|
|
||||||
MxValue value,
|
|
||||||
MxValue timestampValue,
|
|
||||||
int userId,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
MxCommandReply reply = await Write2RawAsync(
|
|
||||||
serverHandle,
|
|
||||||
itemHandle,
|
|
||||||
value,
|
|
||||||
timestampValue,
|
|
||||||
userId,
|
|
||||||
cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> Write2RawAsync(
|
|
||||||
int serverHandle,
|
|
||||||
int itemHandle,
|
|
||||||
MxValue value,
|
|
||||||
MxValue timestampValue,
|
|
||||||
int userId,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(value);
|
|
||||||
ArgumentNullException.ThrowIfNull(timestampValue);
|
|
||||||
|
|
||||||
return InvokeCommandAsync(
|
|
||||||
new MxCommand
|
|
||||||
{
|
|
||||||
Kind = MxCommandKind.Write2,
|
|
||||||
Write2 = new Write2Command
|
|
||||||
{
|
|
||||||
ServerHandle = serverHandle,
|
|
||||||
ItemHandle = itemHandle,
|
|
||||||
Value = value,
|
|
||||||
TimestampValue = timestampValue,
|
|
||||||
UserId = userId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<MxCommandReply> InvokeAsync(
|
|
||||||
MxCommandRequest request,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
ArgumentNullException.ThrowIfNull(request);
|
|
||||||
return _client.InvokeAsync(request, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
|
||||||
ulong afterWorkerSequence = 0,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
return _client.StreamEventsAsync(
|
|
||||||
new StreamEventsRequest
|
|
||||||
{
|
|
||||||
SessionId = SessionId,
|
|
||||||
AfterWorkerSequence = afterWorkerSequence,
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async ValueTask DisposeAsync()
|
|
||||||
{
|
|
||||||
await CloseAsync().ConfigureAwait(false);
|
|
||||||
_closeLock.Dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
private Task<MxCommandReply> InvokeCommandAsync(
|
|
||||||
MxCommand command,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return _client.InvokeAsync(
|
|
||||||
new MxCommandRequest
|
|
||||||
{
|
|
||||||
SessionId = SessionId,
|
|
||||||
ClientCorrelationId = Guid.NewGuid().ToString("N"),
|
|
||||||
Command = command,
|
|
||||||
},
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
public sealed class MxGatewaySessionException : MxGatewayException
|
|
||||||
{
|
|
||||||
public MxGatewaySessionException(
|
|
||||||
string message,
|
|
||||||
string? sessionId = null,
|
|
||||||
string? correlationId = null,
|
|
||||||
ProtocolStatus? protocolStatus = null,
|
|
||||||
int? hResult = null,
|
|
||||||
IReadOnlyList<MxStatusProxy>? statuses = null,
|
|
||||||
Exception? innerException = null)
|
|
||||||
: base(
|
|
||||||
message,
|
|
||||||
sessionId,
|
|
||||||
correlationId,
|
|
||||||
protocolStatus,
|
|
||||||
hResult,
|
|
||||||
statuses ?? [],
|
|
||||||
innerException)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
|
||||||
|
|
||||||
public sealed class MxGatewayWorkerException : MxGatewayException
|
|
||||||
{
|
|
||||||
public MxGatewayWorkerException(
|
|
||||||
string message,
|
|
||||||
string? sessionId = null,
|
|
||||||
string? correlationId = null,
|
|
||||||
ProtocolStatus? protocolStatus = null,
|
|
||||||
int? hResult = null,
|
|
||||||
IReadOnlyList<MxStatusProxy>? statuses = null,
|
|
||||||
Exception? innerException = null)
|
|
||||||
: base(
|
|
||||||
message,
|
|
||||||
sessionId,
|
|
||||||
correlationId,
|
|
||||||
protocolStatus,
|
|
||||||
hResult,
|
|
||||||
statuses ?? [],
|
|
||||||
innerException)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
using System.Runtime.CompilerServices;
|
|
||||||
|
|
||||||
[assembly: InternalsVisibleTo("MxGateway.Client.Tests")]
|
|
||||||
+233
-15
@@ -7,11 +7,11 @@ CLI, and unit tests.
|
|||||||
|
|
||||||
| Project | Purpose |
|
| Project | Purpose |
|
||||||
|---------|---------|
|
|---------|---------|
|
||||||
| `MxGateway.Client` | .NET 10 library entry point, raw gRPC calls, and session helpers. |
|
| `ZB.MOM.WW.MxGateway.Client` | .NET 10 library entry point, raw gRPC calls, and session helpers. |
|
||||||
| `MxGateway.Client.Cli` | Test CLI for smoke and diagnostic commands. |
|
| `ZB.MOM.WW.MxGateway.Client.Cli` | Test CLI for smoke and diagnostic commands. |
|
||||||
| `MxGateway.Client.Tests` | Unit tests for client options, generated contract wiring, auth metadata, session helpers, cancellation, and event streaming. |
|
| `ZB.MOM.WW.MxGateway.Client.Tests` | Unit tests for client options, generated contract wiring, auth metadata, session helpers, cancellation, and event streaming. |
|
||||||
|
|
||||||
The projects reference `src/MxGateway.Contracts/MxGateway.Contracts.csproj` so
|
The projects reference `src/ZB.MOM.WW.MxGateway.Contracts/ZB.MOM.WW.MxGateway.Contracts.csproj` so
|
||||||
the client compiles against the same generated protobuf and gRPC types as the
|
the client compiles against the same generated protobuf and gRPC types as the
|
||||||
gateway. `clients/dotnet/generated` remains reserved for generator output if a
|
gateway. `clients/dotnet/generated` remains reserved for generator output if a
|
||||||
future client build switches to client-local `Grpc.Tools` generation.
|
future client build switches to client-local `Grpc.Tools` generation.
|
||||||
@@ -19,8 +19,31 @@ future client build switches to client-local `Grpc.Tools` generation.
|
|||||||
## Build And Test
|
## Build And Test
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
dotnet build clients/dotnet/MxGateway.Client.sln
|
dotnet build clients/dotnet/ZB.MOM.WW.MxGateway.Client.slnx
|
||||||
dotnet test clients/dotnet/MxGateway.Client.sln --no-build
|
dotnet test clients/dotnet/ZB.MOM.WW.MxGateway.Client.slnx --no-build
|
||||||
|
```
|
||||||
|
|
||||||
|
## Packaging
|
||||||
|
|
||||||
|
Create local library and CLI artifacts from the repository root:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$dotnetPackageOutput = Join-Path (Get-Location) 'artifacts/clients/dotnet'
|
||||||
|
dotnet pack clients/dotnet/ZB.MOM.WW.MxGateway.Client/ZB.MOM.WW.MxGateway.Client.csproj -c Release -p:PackageOutputPath="$dotnetPackageOutput"
|
||||||
|
dotnet publish clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/ZB.MOM.WW.MxGateway.Client.Cli.csproj -c Release -o artifacts/clients/dotnet/mxgw-dotnet
|
||||||
|
```
|
||||||
|
|
||||||
|
The library package references the shared contracts project at build time. The
|
||||||
|
published CLI runs from `artifacts/clients/dotnet/mxgw-dotnet`.
|
||||||
|
|
||||||
|
## Regenerating Protobuf Bindings
|
||||||
|
|
||||||
|
The .NET client uses the generated C# types from
|
||||||
|
`src/ZB.MOM.WW.MxGateway.Contracts/Generated`. Regenerate those files through the
|
||||||
|
contracts project:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
dotnet build src/ZB.MOM.WW.MxGateway.Contracts/ZB.MOM.WW.MxGateway.Contracts.csproj
|
||||||
```
|
```
|
||||||
|
|
||||||
## Client Usage
|
## Client Usage
|
||||||
@@ -61,6 +84,15 @@ messages. `MxGatewaySession.OpenSessionReply` keeps the raw session-open reply
|
|||||||
available, and command helpers have `*RawAsync` variants when callers need the
|
available, and command helpers have `*RawAsync` variants when callers need the
|
||||||
complete `MxCommandReply`.
|
complete `MxCommandReply`.
|
||||||
|
|
||||||
|
For alarms, the client exposes `QueryActiveAlarmsAsync` (one-shot snapshot of
|
||||||
|
the active alarms the gateway's central monitor currently holds),
|
||||||
|
`StreamAlarmsAsync` (server-streaming feed of alarm-state-change messages
|
||||||
|
keyed by the same monitor), and `AcknowledgeAlarmAsync` (ack by alarm
|
||||||
|
reference, optional comment, ack target). All three accept a cancellation
|
||||||
|
token and pass through the `MxGateway:Alarms` configuration on the
|
||||||
|
server — when alarms are disabled, the gateway returns an empty list / empty
|
||||||
|
stream rather than failing.
|
||||||
|
|
||||||
`MxGatewaySession.CloseAsync` is explicit and idempotent. Repeated calls return
|
`MxGatewaySession.CloseAsync` is explicit and idempotent. Repeated calls return
|
||||||
the first `CloseSessionReply` instead of sending another close request.
|
the first `CloseSessionReply` instead of sending another close request.
|
||||||
|
|
||||||
@@ -94,18 +126,204 @@ reply.
|
|||||||
The test CLI supports deterministic JSON output for automation:
|
The test CLI supports deterministic JSON output for automation:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
dotnet run --project clients/dotnet/MxGateway.Client.Cli -- version --json
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- version --json
|
||||||
dotnet run --project clients/dotnet/MxGateway.Client.Cli -- open-session --endpoint http://localhost:5000 --api-key-env MXGATEWAY_API_KEY --json
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- open-session --endpoint http://localhost:5000 --api-key-env MXGATEWAY_API_KEY --json
|
||||||
dotnet run --project clients/dotnet/MxGateway.Client.Cli -- register --session-id <id> --client-name mxgw-dotnet-cli --json
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- register --session-id <id> --client-name mxgw-dotnet-cli --json
|
||||||
dotnet run --project clients/dotnet/MxGateway.Client.Cli -- add-item --session-id <id> --server-handle 1 --item Area001.Pump001.Speed --json
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- add-item --session-id <id> --server-handle 1 --item Area001.Pump001.Speed --json
|
||||||
dotnet run --project clients/dotnet/MxGateway.Client.Cli -- advise --session-id <id> --server-handle 1 --item-handle 1 --json
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- advise --session-id <id> --server-handle 1 --item-handle 1 --json
|
||||||
dotnet run --project clients/dotnet/MxGateway.Client.Cli -- write --session-id <id> --server-handle 1 --item-handle 1 --type int32 --value 123 --json
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- write --session-id <id> --server-handle 1 --item-handle 1 --type int32 --value 123 --json
|
||||||
dotnet run --project clients/dotnet/MxGateway.Client.Cli -- write2 --session-id <id> --server-handle 1 --item-handle 1 --type int32 --value 123 --timestamp 2026-01-01T00:00:00Z --json
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- write2 --session-id <id> --server-handle 1 --item-handle 1 --type int32 --value 123 --timestamp 2026-01-01T00:00:00Z --json
|
||||||
dotnet run --project clients/dotnet/MxGateway.Client.Cli -- stream-events --session-id <id> --max-events 1 --json
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- stream-events --session-id <id> --max-events 1 --json
|
||||||
dotnet run --project clients/dotnet/MxGateway.Client.Cli -- smoke --endpoint http://localhost:5000 --api-key-env MXGATEWAY_API_KEY --item Area001.Pump001.Speed --json
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- stream-alarms --filter-prefix Area001 --max-events 1 --json
|
||||||
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- acknowledge-alarm --reference "\\Galaxy\Area001.Pump001.PumpFault" --comment "ack from cli" --operator operator1 --json
|
||||||
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- smoke --endpoint http://localhost:5000 --api-key-env MXGATEWAY_API_KEY --item Area001.Pump001.Speed --json
|
||||||
```
|
```
|
||||||
|
|
||||||
`smoke` opens a session, registers a client, adds one item, advises it,
|
`smoke` opens a session, registers a client, adds one item, advises it,
|
||||||
optionally writes a value when `--type` and `--value` are supplied, reads a
|
optionally writes a value when `--type` and `--value` are supplied, reads a
|
||||||
bounded event stream, and closes the session in a `finally` block. CLI error
|
bounded event stream, and closes the session in a `finally` block. CLI error
|
||||||
output redacts API keys supplied through `--api-key`.
|
output redacts API keys supplied through `--api-key`.
|
||||||
|
|
||||||
|
## Galaxy Repository Browse
|
||||||
|
|
||||||
|
`GalaxyRepositoryClient` is a separate read-only wrapper around the
|
||||||
|
`GalaxyRepository` gRPC service exposed by the same gateway. It shares the API
|
||||||
|
key auth interceptor with `MxGatewayClient` and requires the `metadata:read`
|
||||||
|
scope server-side. Use it to probe the ZB SQL connection, watch
|
||||||
|
`time_of_last_deploy` for redeployments, and enumerate the deployed Galaxy
|
||||||
|
object hierarchy plus each object's dynamic attributes.
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
await using GalaxyRepositoryClient repository = GalaxyRepositoryClient.Create(
|
||||||
|
new MxGatewayClientOptions
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("http://localhost:5000"),
|
||||||
|
ApiKey = apiKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
bool ok = await repository.TestConnectionAsync();
|
||||||
|
DateTime? lastDeploy = await repository.GetLastDeployTimeAsync();
|
||||||
|
|
||||||
|
IReadOnlyList<GalaxyObject> objects = await repository.DiscoverHierarchyAsync();
|
||||||
|
foreach (GalaxyObject galaxyObject in objects)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"{galaxyObject.TagName} ({galaxyObject.ContainedName})");
|
||||||
|
foreach (GalaxyAttribute attribute in galaxyObject.Attributes)
|
||||||
|
{
|
||||||
|
Console.WriteLine($" {attribute.AttributeName} -> {attribute.FullTagReference}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `DiscoverHierarchyOptions` to request a server-side slice without pulling
|
||||||
|
the full Galaxy:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
IReadOnlyList<GalaxyObject> pumps = await repository.DiscoverHierarchyAsync(
|
||||||
|
new DiscoverHierarchyOptions
|
||||||
|
{
|
||||||
|
RootContainedPath = "Area1/Line3",
|
||||||
|
TagNameGlob = "Pump_*",
|
||||||
|
IncludeAttributes = false,
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
The CLI exposes the same operations:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- galaxy-test-connection --endpoint http://localhost:5000 --api-key-env MXGATEWAY_API_KEY --json
|
||||||
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- galaxy-last-deploy --endpoint http://localhost:5000 --api-key-env MXGATEWAY_API_KEY --json
|
||||||
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- galaxy-discover --endpoint http://localhost:5000 --api-key-env MXGATEWAY_API_KEY
|
||||||
|
```
|
||||||
|
|
||||||
|
### Browsing lazily
|
||||||
|
|
||||||
|
For UI trees or OPC UA bridges, use `BrowseChildrenAsync` to walk one level at a
|
||||||
|
time instead of paging the full hierarchy. Pass an empty request for root objects;
|
||||||
|
subsequent calls supply `ParentGobjectId`, `ParentTagName`, or
|
||||||
|
`ParentContainedPath`. Each child's `ChildHasChildren[i]` tells you whether to
|
||||||
|
draw an expand triangle. Filter fields match `DiscoverHierarchy`. See
|
||||||
|
[Galaxy Repository](../../docs/GalaxyRepository.md#browsechildren) for full
|
||||||
|
request and filter semantics.
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
BrowseChildrenReply roots = await repository.BrowseChildrenAsync(
|
||||||
|
new BrowseChildrenRequest());
|
||||||
|
|
||||||
|
for (int i = 0; i < roots.Children.Count; i++)
|
||||||
|
{
|
||||||
|
GalaxyObject child = roots.Children[i];
|
||||||
|
bool hasChildren = roots.ChildHasChildren[i];
|
||||||
|
Console.WriteLine($"{child.TagName} expand={hasChildren}");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### High-level walker
|
||||||
|
|
||||||
|
For UI trees, the client provides a `LazyBrowseNode` walker that handles
|
||||||
|
sibling pagination and the `child_has_children` hint for you:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
await using GalaxyRepositoryClient repository = GalaxyRepositoryClient.Create(
|
||||||
|
new MxGatewayClientOptions { Endpoint = new Uri("http://localhost:5000"), ApiKey = apiKey });
|
||||||
|
IReadOnlyList<LazyBrowseNode> roots = await repository.BrowseAsync();
|
||||||
|
foreach (LazyBrowseNode root in roots)
|
||||||
|
{
|
||||||
|
if (root.HasChildrenHint)
|
||||||
|
{
|
||||||
|
await root.ExpandAsync();
|
||||||
|
}
|
||||||
|
foreach (LazyBrowseNode child in root.Children)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"{child.Object.TagName} ({(child.HasChildrenHint ? "has children" : "leaf")})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`ExpandAsync` is idempotent — calling it twice fires only one RPC,
|
||||||
|
and is safe under concurrent callers. To refresh after a Galaxy redeploy, call
|
||||||
|
`BrowseAsync` again from the root.
|
||||||
|
|
||||||
|
### Watching deploy events
|
||||||
|
|
||||||
|
`WatchDeployEventsAsync` opens the `WatchDeployEvents` server-streaming RPC. The
|
||||||
|
server emits a bootstrap event with the current state on subscribe, then one
|
||||||
|
event per new `time_of_last_deploy`. Pass a `lastSeenDeployTime` to suppress the
|
||||||
|
bootstrap when the caller already holds the current deploy time. Use the
|
||||||
|
monotonic `Sequence` field to detect dropped events: gaps mean the
|
||||||
|
per-subscriber server-side buffer overflowed and the caller should reconcile.
|
||||||
|
|
||||||
|
Streaming RPCs are not wrapped by the unary safe-read retry pipeline. The
|
||||||
|
caller is responsible for reopening the stream on transient failures.
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
await using GalaxyRepositoryClient repository = GalaxyRepositoryClient.Create(options);
|
||||||
|
|
||||||
|
DateTimeOffset? lastSeen = null;
|
||||||
|
await foreach (DeployEvent evt in repository.WatchDeployEventsAsync(
|
||||||
|
lastSeen,
|
||||||
|
cancellationToken))
|
||||||
|
{
|
||||||
|
Console.WriteLine(
|
||||||
|
$"seq={evt.Sequence} objects={evt.ObjectCount} attributes={evt.AttributeCount}");
|
||||||
|
if (evt.TimeOfLastDeployPresent && evt.TimeOfLastDeploy is not null)
|
||||||
|
{
|
||||||
|
lastSeen = evt.TimeOfLastDeploy.ToDateTimeOffset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The CLI counterpart streams events until Ctrl+C (or `--max-events`):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- galaxy-watch --endpoint http://localhost:5000 --api-key-env MXGATEWAY_API_KEY
|
||||||
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- galaxy-watch --endpoint http://localhost:5000 --api-key-env MXGATEWAY_API_KEY --last-seen-deploy-time 2026-04-28T14:30:00Z --json
|
||||||
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- galaxy-watch --endpoint http://localhost:5000 --api-key-env MXGATEWAY_API_KEY --max-events 5 --json
|
||||||
|
```
|
||||||
|
|
||||||
|
Use TLS options for a secured gateway:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- smoke --endpoint https://ZB.MOM.WW.MxGateway.example.local:5001 --tls --ca-file C:\certs\mxgateway-ca.pem --server-name ZB.MOM.WW.MxGateway.example.local --api-key-env MXGATEWAY_API_KEY --item Area001.Pump001.Speed --json
|
||||||
|
```
|
||||||
|
|
||||||
|
## Integration Checks
|
||||||
|
|
||||||
|
Run live checks only when a gateway and MXAccess-backed worker are available:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:MXGATEWAY_INTEGRATION = '1'
|
||||||
|
$env:MXGATEWAY_ENDPOINT = 'http://localhost:5000'
|
||||||
|
$env:MXGATEWAY_API_KEY = '<gateway-api-key>'
|
||||||
|
$env:MXGATEWAY_TEST_ITEM = 'Area001.Pump001.Speed'
|
||||||
|
dotnet run --project clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli -- smoke --endpoint $env:MXGATEWAY_ENDPOINT --api-key-env MXGATEWAY_API_KEY --item $env:MXGATEWAY_TEST_ITEM --json
|
||||||
|
```
|
||||||
|
|
||||||
|
## Installing as a NuGet Package
|
||||||
|
|
||||||
|
The client publishes to the internal Gitea NuGet feed at
|
||||||
|
`https://gitea.dohertylan.com/api/packages/dohertj2/nuget/index.json`.
|
||||||
|
|
||||||
|
Add the feed once:
|
||||||
|
|
||||||
|
````bash
|
||||||
|
dotnet nuget add source https://gitea.dohertylan.com/api/packages/dohertj2/nuget/index.json \
|
||||||
|
--name dohertj2-gitea \
|
||||||
|
--username <gitea-username> \
|
||||||
|
--password <gitea-token-or-password> \
|
||||||
|
--store-password-in-clear-text
|
||||||
|
````
|
||||||
|
|
||||||
|
Then add the package to your project:
|
||||||
|
|
||||||
|
````bash
|
||||||
|
dotnet add package ZB.MOM.WW.MxGateway.Client --version 0.1.0
|
||||||
|
````
|
||||||
|
|
||||||
|
The `ZB.MOM.WW.MxGateway.Contracts` package is pulled in transitively.
|
||||||
|
|
||||||
|
## Related Documentation
|
||||||
|
|
||||||
|
- [Client Packaging](../../docs/ClientPackaging.md)
|
||||||
|
- [Client Proto Generation](../../docs/ClientProtoGeneration.md)
|
||||||
|
- [.NET Client Detailed Design](./DotnetClientDesign.md)
|
||||||
|
|||||||
+22
-1
@@ -1,12 +1,15 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
|
|
||||||
namespace MxGateway.Client.Cli;
|
namespace ZB.MOM.WW.MxGateway.Client.Cli;
|
||||||
|
|
||||||
|
/// <summary>Parses command-line arguments into flags and named values.</summary>
|
||||||
internal sealed class CliArguments
|
internal sealed class CliArguments
|
||||||
{
|
{
|
||||||
private readonly Dictionary<string, string> _values = new(StringComparer.OrdinalIgnoreCase);
|
private readonly Dictionary<string, string> _values = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private readonly HashSet<string> _flags = new(StringComparer.OrdinalIgnoreCase);
|
private readonly HashSet<string> _flags = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
/// <summary>Initializes a new instance by parsing the given command-line arguments.</summary>
|
||||||
|
/// <param name="args">Unparsed command-line arguments; flags prefixed with '--' and values follow their flag.</param>
|
||||||
public CliArguments(IEnumerable<string> args)
|
public CliArguments(IEnumerable<string> args)
|
||||||
{
|
{
|
||||||
string? pendingName = null;
|
string? pendingName = null;
|
||||||
@@ -39,11 +42,15 @@ internal sealed class CliArguments
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns whether the named flag was present in the arguments.</summary>
|
||||||
|
/// <param name="name">The flag name (without '--' prefix).</param>
|
||||||
public bool HasFlag(string name)
|
public bool HasFlag(string name)
|
||||||
{
|
{
|
||||||
return _flags.Contains(name);
|
return _flags.Contains(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns the value for a named argument, or <c>null</c> if absent.</summary>
|
||||||
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
public string? GetOptional(string name)
|
public string? GetOptional(string name)
|
||||||
{
|
{
|
||||||
return _values.TryGetValue(name, out string? value)
|
return _values.TryGetValue(name, out string? value)
|
||||||
@@ -51,6 +58,8 @@ internal sealed class CliArguments
|
|||||||
: null;
|
: null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns the value for a required named argument, or throws if absent.</summary>
|
||||||
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
public string GetRequired(string name)
|
public string GetRequired(string name)
|
||||||
{
|
{
|
||||||
string? value = GetOptional(name);
|
string? value = GetOptional(name);
|
||||||
@@ -62,6 +71,9 @@ internal sealed class CliArguments
|
|||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Parses and returns an int32 argument, or the default value if absent.</summary>
|
||||||
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
|
/// <param name="defaultValue">The default value if the argument is absent; if <c>null</c>, the argument is required.</param>
|
||||||
public int GetInt32(string name, int? defaultValue = null)
|
public int GetInt32(string name, int? defaultValue = null)
|
||||||
{
|
{
|
||||||
string? value = GetOptional(name);
|
string? value = GetOptional(name);
|
||||||
@@ -78,6 +90,9 @@ internal sealed class CliArguments
|
|||||||
return int.Parse(value, CultureInfo.InvariantCulture);
|
return int.Parse(value, CultureInfo.InvariantCulture);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Parses and returns a uint32 argument, or the default value if absent.</summary>
|
||||||
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
|
/// <param name="defaultValue">The default value if the argument is absent.</param>
|
||||||
public uint GetUInt32(string name, uint defaultValue)
|
public uint GetUInt32(string name, uint defaultValue)
|
||||||
{
|
{
|
||||||
string? value = GetOptional(name);
|
string? value = GetOptional(name);
|
||||||
@@ -86,6 +101,9 @@ internal sealed class CliArguments
|
|||||||
: uint.Parse(value, CultureInfo.InvariantCulture);
|
: uint.Parse(value, CultureInfo.InvariantCulture);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Parses and returns a uint64 argument, or the default value if absent.</summary>
|
||||||
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
|
/// <param name="defaultValue">The default value if the argument is absent.</param>
|
||||||
public ulong GetUInt64(string name, ulong defaultValue)
|
public ulong GetUInt64(string name, ulong defaultValue)
|
||||||
{
|
{
|
||||||
string? value = GetOptional(name);
|
string? value = GetOptional(name);
|
||||||
@@ -94,6 +112,9 @@ internal sealed class CliArguments
|
|||||||
: ulong.Parse(value, CultureInfo.InvariantCulture);
|
: ulong.Parse(value, CultureInfo.InvariantCulture);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Parses and returns a TimeSpan argument, or the default value if absent. Supports "ms", "s", and standard TimeSpan format.</summary>
|
||||||
|
/// <param name="name">The argument name (without '--' prefix).</param>
|
||||||
|
/// <param name="defaultValue">The default value if the argument is absent.</param>
|
||||||
public TimeSpan GetDuration(string name, TimeSpan defaultValue)
|
public TimeSpan GetDuration(string name, TimeSpan defaultValue)
|
||||||
{
|
{
|
||||||
string? value = GetOptional(name);
|
string? value = GetOptional(name);
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Cli;
|
||||||
|
|
||||||
|
public interface IMxGatewayCliClient : IAsyncDisposable
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Opens a new gateway session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Session open request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The session open reply.</returns>
|
||||||
|
Task<OpenSessionReply> OpenSessionAsync(
|
||||||
|
OpenSessionRequest request,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Closes an open gateway session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Session close request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The session close reply.</returns>
|
||||||
|
Task<CloseSessionReply> CloseSessionAsync(
|
||||||
|
CloseSessionRequest request,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Invokes an MXAccess command on the session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The command request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The command reply.</returns>
|
||||||
|
Task<MxCommandReply> InvokeAsync(
|
||||||
|
MxCommandRequest request,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Streams events from the gateway session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The stream events request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>An async enumerable of events.</returns>
|
||||||
|
IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
||||||
|
StreamEventsRequest request,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Acknowledges an active MXAccess alarm condition through the gateway.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The acknowledge request — alarm reference, comment, operator user.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The acknowledge reply with protocol + native MxStatus.</returns>
|
||||||
|
Task<AcknowledgeAlarmReply> AcknowledgeAlarmAsync(
|
||||||
|
AcknowledgeAlarmRequest request,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attaches to the gateway's central alarm feed — the current active-alarm
|
||||||
|
/// snapshot followed by live transitions.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The stream request, optionally scoped by alarm-reference prefix.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>An async enumerable of alarm feed messages.</returns>
|
||||||
|
IAsyncEnumerable<AlarmFeedMessage> StreamAlarmsAsync(
|
||||||
|
StreamAlarmsRequest request,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tests connection to the Galaxy Repository.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The connection test request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The connection test reply.</returns>
|
||||||
|
Task<TestConnectionReply> GalaxyTestConnectionAsync(
|
||||||
|
TestConnectionRequest request,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the last deployment time from the Galaxy Repository.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The last deploy time request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The last deploy time reply.</returns>
|
||||||
|
Task<GetLastDeployTimeReply> GalaxyGetLastDeployTimeAsync(
|
||||||
|
GetLastDeployTimeRequest request,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Discovers the Galaxy Repository hierarchy.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The discover hierarchy request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The discover hierarchy reply.</returns>
|
||||||
|
Task<DiscoverHierarchyReply> GalaxyDiscoverHierarchyAsync(
|
||||||
|
DiscoverHierarchyRequest request,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Watches for deployment events from the Galaxy Repository.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The watch deploy events request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>An async enumerable of deployment events.</returns>
|
||||||
|
IAsyncEnumerable<DeployEvent> GalaxyWatchDeployEventsAsync(
|
||||||
|
WatchDeployEventsRequest request,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Client;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Cli;
|
||||||
|
|
||||||
|
internal sealed class MxGatewayCliClientAdapter : IMxGatewayCliClient
|
||||||
|
{
|
||||||
|
private readonly MxGatewayClient _client;
|
||||||
|
private readonly Lazy<GalaxyRepositoryClient> _galaxyClient;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="MxGatewayCliClientAdapter"/> that bridges the CLI to the gateway client.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="client">The gateway client to adapt.</param>
|
||||||
|
public MxGatewayCliClientAdapter(MxGatewayClient client)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
_galaxyClient = new Lazy<GalaxyRepositoryClient>(
|
||||||
|
() => GalaxyRepositoryClient.Create(_client.Options));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<OpenSessionReply> OpenSessionAsync(
|
||||||
|
OpenSessionRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _client.OpenSessionRawAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<CloseSessionReply> CloseSessionAsync(
|
||||||
|
CloseSessionRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _client.CloseSessionRawAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<MxCommandReply> InvokeAsync(
|
||||||
|
MxCommandRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _client.InvokeAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
||||||
|
StreamEventsRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _client.StreamEventsAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<AcknowledgeAlarmReply> AcknowledgeAlarmAsync(
|
||||||
|
AcknowledgeAlarmRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _client.AcknowledgeAlarmAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public IAsyncEnumerable<AlarmFeedMessage> StreamAlarmsAsync(
|
||||||
|
StreamAlarmsRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _client.StreamAlarmsAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<TestConnectionReply> GalaxyTestConnectionAsync(
|
||||||
|
TestConnectionRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _galaxyClient.Value.TestConnectionRawAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<GetLastDeployTimeReply> GalaxyGetLastDeployTimeAsync(
|
||||||
|
GetLastDeployTimeRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _galaxyClient.Value.GetLastDeployTimeRawAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<DiscoverHierarchyReply> GalaxyDiscoverHierarchyAsync(
|
||||||
|
DiscoverHierarchyRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _galaxyClient.Value.DiscoverHierarchyRawAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public IAsyncEnumerable<DeployEvent> GalaxyWatchDeployEventsAsync(
|
||||||
|
WatchDeployEventsRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _galaxyClient.Value.WatchDeployEventsRawAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
if (_galaxyClient.IsValueCreated)
|
||||||
|
{
|
||||||
|
await _galaxyClient.Value.DisposeAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _client.DisposeAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Cli;
|
||||||
|
|
||||||
|
/// <summary>Utility to redact API keys from error messages for safe output.</summary>
|
||||||
|
internal static class MxGatewayCliSecretRedactor
|
||||||
|
{
|
||||||
|
/// <summary>Replaces occurrences of the API key in the value with a redacted placeholder.</summary>
|
||||||
|
/// <param name="value">The message text to redact.</param>
|
||||||
|
/// <param name="apiKey">The API key to remove; no redaction if null or empty.</param>
|
||||||
|
public static string Redact(string value, string? apiKey)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(apiKey))
|
||||||
|
{
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return value.Replace(apiKey, "[redacted]", StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
using MxGateway.Client.Cli;
|
using ZB.MOM.WW.MxGateway.Client.Cli;
|
||||||
|
|
||||||
return await MxGatewayClientCli.RunAsync(args, Console.Out, Console.Error);
|
return await MxGatewayClientCli.RunAsync(args, Console.Out, Console.Error);
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\MxGateway.Client\MxGateway.Client.csproj" />
|
<ProjectReference Include="..\ZB.MOM.WW.MxGateway.Client\ZB.MOM.WW.MxGateway.Client.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using Grpc.Net.Client;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Live smoke tests for the BrowseChildren RPC. Skipped by default; set
|
||||||
|
/// MXGATEWAY_API_KEY and MXGATEWAY_ENDPOINT to run against a real gateway.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class BrowseChildrenSmokeTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that BrowseChildren returns a non-zero cache sequence and
|
||||||
|
/// a consistent children/child-has-children count from a live gateway.
|
||||||
|
/// </summary>
|
||||||
|
[Fact(Skip = "Set MXGATEWAY_API_KEY and MXGATEWAY_ENDPOINT to enable.")]
|
||||||
|
public async Task BrowseChildren_LiveGateway_ReturnsRootsWithCacheSequence()
|
||||||
|
{
|
||||||
|
string? apiKey = Environment.GetEnvironmentVariable("MXGATEWAY_API_KEY");
|
||||||
|
string endpoint = Environment.GetEnvironmentVariable("MXGATEWAY_ENDPOINT") ?? "http://localhost:5120";
|
||||||
|
|
||||||
|
Assert.False(string.IsNullOrEmpty(apiKey), "MXGATEWAY_API_KEY must be set.");
|
||||||
|
|
||||||
|
using GrpcChannel channel = GrpcChannel.ForAddress(endpoint);
|
||||||
|
GalaxyRepository.GalaxyRepositoryClient client = new(channel);
|
||||||
|
|
||||||
|
Metadata headers = new() { { "authorization", $"Bearer {apiKey}" } };
|
||||||
|
BrowseChildrenReply reply = await client.BrowseChildrenAsync(new BrowseChildrenRequest(), headers);
|
||||||
|
|
||||||
|
Assert.True(reply.CacheSequence > 0UL);
|
||||||
|
Assert.Equal(reply.Children.Count, reply.ChildHasChildren.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fake Galaxy Repository client transport for testing.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class FakeGalaxyRepositoryTransport(MxGatewayClientOptions options) : IGalaxyRepositoryClientTransport
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the gateway client options.
|
||||||
|
/// </summary>
|
||||||
|
public MxGatewayClientOptions Options { get; } = options;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the raw gRPC client; always null for the fake.
|
||||||
|
/// </summary>
|
||||||
|
public GalaxyRepository.GalaxyRepositoryClient? RawClient => null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of TestConnection RPC calls made by the client.
|
||||||
|
/// </summary>
|
||||||
|
public List<(TestConnectionRequest Request, CallOptions CallOptions)> TestConnectionCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of GetLastDeployTime RPC calls made by the client.
|
||||||
|
/// </summary>
|
||||||
|
public List<(GetLastDeployTimeRequest Request, CallOptions CallOptions)> GetLastDeployTimeCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of DiscoverHierarchy RPC calls made by the client.
|
||||||
|
/// </summary>
|
||||||
|
public List<(DiscoverHierarchyRequest Request, CallOptions CallOptions)> DiscoverHierarchyCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the reply to return from TestConnection; defaults to successful response.
|
||||||
|
/// </summary>
|
||||||
|
public TestConnectionReply TestConnectionReply { get; set; } = new() { Ok = true };
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the reply to return from GetLastDeployTime; defaults to no deploy time present.
|
||||||
|
/// </summary>
|
||||||
|
public GetLastDeployTimeReply GetLastDeployTimeReply { get; set; } = new() { Present = false };
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the reply to return from DiscoverHierarchy; defaults to empty response.
|
||||||
|
/// </summary>
|
||||||
|
public DiscoverHierarchyReply DiscoverHierarchyReply { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>Gets the queue of discover hierarchy replies; dequeued in FIFO order.</summary>
|
||||||
|
public Queue<DiscoverHierarchyReply> DiscoverHierarchyReplies { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the queue of exceptions to throw from TestConnection; dequeued in FIFO order.
|
||||||
|
/// </summary>
|
||||||
|
public Queue<Exception> TestConnectionExceptions { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the queue of exceptions to throw from GetLastDeployTime; dequeued in FIFO order.
|
||||||
|
/// </summary>
|
||||||
|
public Queue<Exception> GetLastDeployTimeExceptions { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the queue of exceptions to throw from DiscoverHierarchy; dequeued in FIFO order.
|
||||||
|
/// </summary>
|
||||||
|
public Queue<Exception> DiscoverHierarchyExceptions { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records the request and either throws a queued exception or returns the configured reply.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The TestConnectionRequest to process.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public Task<TestConnectionReply> TestConnectionAsync(
|
||||||
|
TestConnectionRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
TestConnectionCalls.Add((request, callOptions));
|
||||||
|
if (TestConnectionExceptions.TryDequeue(out Exception? exception))
|
||||||
|
{
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(TestConnectionReply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records the request and either throws a queued exception or returns the configured reply.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The GetLastDeployTimeRequest to process.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public Task<GetLastDeployTimeReply> GetLastDeployTimeAsync(
|
||||||
|
GetLastDeployTimeRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
GetLastDeployTimeCalls.Add((request, callOptions));
|
||||||
|
if (GetLastDeployTimeExceptions.TryDequeue(out Exception? exception))
|
||||||
|
{
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(GetLastDeployTimeReply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records the request and either throws a queued exception or returns the configured reply.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The DiscoverHierarchyRequest to process.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public Task<DiscoverHierarchyReply> DiscoverHierarchyAsync(
|
||||||
|
DiscoverHierarchyRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
DiscoverHierarchyCalls.Add((request, callOptions));
|
||||||
|
if (DiscoverHierarchyExceptions.TryDequeue(out Exception? exception))
|
||||||
|
{
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(
|
||||||
|
DiscoverHierarchyReplies.TryDequeue(out DiscoverHierarchyReply? reply)
|
||||||
|
? reply
|
||||||
|
: DiscoverHierarchyReply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Records BrowseChildren RPC calls made by the client.</summary>
|
||||||
|
public List<(BrowseChildrenRequest Request, CallOptions CallOptions)> BrowseChildrenCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>Default reply returned from BrowseChildren when the queue is empty.</summary>
|
||||||
|
public BrowseChildrenReply BrowseChildrenReply { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>Queue of replies returned from BrowseChildren; dequeued in FIFO order.</summary>
|
||||||
|
public Queue<BrowseChildrenReply> BrowseChildrenReplies { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>Queue of exceptions to throw from BrowseChildren; dequeued in FIFO order.</summary>
|
||||||
|
public Queue<Exception> BrowseChildrenExceptions { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records the request and either throws a queued exception or returns the configured reply.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The BrowseChildrenRequest to process.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public Task<BrowseChildrenReply> BrowseChildrenAsync(
|
||||||
|
BrowseChildrenRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
BrowseChildrenCalls.Add((request, callOptions));
|
||||||
|
if (BrowseChildrenExceptions.TryDequeue(out Exception? exception))
|
||||||
|
{
|
||||||
|
return Task.FromException<BrowseChildrenReply>(exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(
|
||||||
|
BrowseChildrenReplies.TryDequeue(out BrowseChildrenReply? reply)
|
||||||
|
? reply
|
||||||
|
: BrowseChildrenReply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of WatchDeployEvents RPC calls made by the client.
|
||||||
|
/// </summary>
|
||||||
|
public List<(WatchDeployEventsRequest Request, CallOptions CallOptions)> WatchDeployEventsCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the list of events to stream from WatchDeployEvents.
|
||||||
|
/// </summary>
|
||||||
|
public List<DeployEvent> WatchDeployEvents { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the exception to throw from WatchDeployEvents, if any.
|
||||||
|
/// </summary>
|
||||||
|
public Exception? WatchDeployEventsException { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When set, awaited before each event yield so tests can observe cancellation
|
||||||
|
/// mid-stream. Receives the call's cancellation token.
|
||||||
|
/// </summary>
|
||||||
|
public Func<CancellationToken, Task>? WatchDeployEventsBeforeYield { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records the request and streams events, checking for queued exceptions and calling WatchDeployEventsBeforeYield before each event.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The WatchDeployEventsRequest to process.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public async IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
|
||||||
|
WatchDeployEventsRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
WatchDeployEventsCalls.Add((request, callOptions));
|
||||||
|
|
||||||
|
if (WatchDeployEventsException is not null)
|
||||||
|
{
|
||||||
|
throw WatchDeployEventsException;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (DeployEvent deployEvent in WatchDeployEvents)
|
||||||
|
{
|
||||||
|
if (WatchDeployEventsBeforeYield is not null)
|
||||||
|
{
|
||||||
|
await WatchDeployEventsBeforeYield(callOptions.CancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
callOptions.CancellationToken.ThrowIfCancellationRequested();
|
||||||
|
yield return deployEvent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fake implementation of IMxGatewayClientTransport for testing.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMxGatewayClientTransport
|
||||||
|
{
|
||||||
|
private readonly Queue<MxCommandReply> _invokeReplies = new();
|
||||||
|
private readonly List<MxEvent> _events = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the gateway client options.
|
||||||
|
/// </summary>
|
||||||
|
public MxGatewayClientOptions Options { get; } = options;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets null, since this is a test fake without a real gRPC client.
|
||||||
|
/// </summary>
|
||||||
|
public MxAccessGateway.MxAccessGatewayClient? RawClient => null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of captured OpenSessionAsync calls.
|
||||||
|
/// </summary>
|
||||||
|
public List<(OpenSessionRequest Request, CallOptions CallOptions)> OpenSessionCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of captured CloseSessionAsync calls.
|
||||||
|
/// </summary>
|
||||||
|
public List<(CloseSessionRequest Request, CallOptions CallOptions)> CloseSessionCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of captured InvokeAsync calls.
|
||||||
|
/// </summary>
|
||||||
|
public List<(MxCommandRequest Request, CallOptions CallOptions)> InvokeCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of captured StreamEventsAsync calls.
|
||||||
|
/// </summary>
|
||||||
|
public List<(StreamEventsRequest Request, CallOptions CallOptions)> StreamEventsCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of captured AcknowledgeAlarmAsync calls.
|
||||||
|
/// </summary>
|
||||||
|
public List<(AcknowledgeAlarmRequest Request, CallOptions CallOptions)> AcknowledgeAlarmCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of captured QueryActiveAlarmsAsync calls.
|
||||||
|
/// </summary>
|
||||||
|
public List<(QueryActiveAlarmsRequest Request, CallOptions CallOptions)> QueryActiveAlarmsCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of captured StreamAlarmsAsync calls.
|
||||||
|
/// </summary>
|
||||||
|
public List<(StreamAlarmsRequest Request, CallOptions CallOptions)> StreamAlarmsCalls { get; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the queue of exceptions to throw from AcknowledgeAlarmAsync.
|
||||||
|
/// </summary>
|
||||||
|
public Queue<Exception> AcknowledgeAlarmExceptions { get; } = new();
|
||||||
|
|
||||||
|
private readonly Queue<AcknowledgeAlarmReply> _acknowledgeReplies = new();
|
||||||
|
private readonly List<ActiveAlarmSnapshot> _activeAlarmSnapshots = [];
|
||||||
|
private readonly List<AlarmFeedMessage> _alarmFeedMessages = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the reply to return from OpenSessionAsync.
|
||||||
|
/// </summary>
|
||||||
|
public OpenSessionReply OpenSessionReply { get; set; } = new()
|
||||||
|
{
|
||||||
|
SessionId = "session-fixture",
|
||||||
|
BackendName = "mxaccess-worker",
|
||||||
|
GatewayProtocolVersion = 1,
|
||||||
|
WorkerProtocolVersion = 1,
|
||||||
|
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the reply to return from CloseSessionAsync.
|
||||||
|
/// </summary>
|
||||||
|
public CloseSessionReply CloseSessionReply { get; set; } = new()
|
||||||
|
{
|
||||||
|
SessionId = "session-fixture",
|
||||||
|
FinalState = SessionState.Closed,
|
||||||
|
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the queue of exceptions to throw from OpenSessionAsync.
|
||||||
|
/// </summary>
|
||||||
|
public Queue<Exception> OpenSessionExceptions { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the queue of exceptions to throw from CloseSessionAsync.
|
||||||
|
/// </summary>
|
||||||
|
public Queue<Exception> CloseSessionExceptions { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the queue of exceptions to throw from InvokeAsync.
|
||||||
|
/// </summary>
|
||||||
|
public Queue<Exception> InvokeExceptions { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that the OpenSessionAsync call is recorded and returns the configured reply.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The OpenSessionRequest to process.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public Task<OpenSessionReply> OpenSessionAsync(
|
||||||
|
OpenSessionRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
OpenSessionCalls.Add((request, callOptions));
|
||||||
|
if (OpenSessionExceptions.TryDequeue(out Exception? exception))
|
||||||
|
{
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(OpenSessionReply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that the CloseSessionAsync call is recorded and returns the configured reply.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The CloseSessionRequest to process.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public Task<CloseSessionReply> CloseSessionAsync(
|
||||||
|
CloseSessionRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
CloseSessionCalls.Add((request, callOptions));
|
||||||
|
if (CloseSessionExceptions.TryDequeue(out Exception? exception))
|
||||||
|
{
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(CloseSessionReply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that the InvokeAsync call is recorded and returns the next enqueued reply.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The MxCommandRequest to process.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public Task<MxCommandReply> InvokeAsync(
|
||||||
|
MxCommandRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
InvokeCalls.Add((request, callOptions));
|
||||||
|
if (InvokeExceptions.TryDequeue(out Exception? exception))
|
||||||
|
{
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(_invokeReplies.Dequeue());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that the StreamEventsAsync call is recorded and yields all enqueued events.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The StreamEventsRequest to process.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public async IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
||||||
|
StreamEventsRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
StreamEventsCalls.Add((request, callOptions));
|
||||||
|
|
||||||
|
foreach (MxEvent gatewayEvent in _events)
|
||||||
|
{
|
||||||
|
callOptions.CancellationToken.ThrowIfCancellationRequested();
|
||||||
|
await Task.Yield();
|
||||||
|
yield return gatewayEvent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Enqueues a reply to be returned from the next InvokeAsync call.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="reply">The reply to enqueue.</param>
|
||||||
|
public void AddInvokeReply(MxCommandReply reply)
|
||||||
|
{
|
||||||
|
_invokeReplies.Enqueue(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Enqueues an event to be yielded from StreamEventsAsync.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="gatewayEvent">The event to enqueue.</param>
|
||||||
|
public void AddEvent(MxEvent gatewayEvent)
|
||||||
|
{
|
||||||
|
_events.Add(gatewayEvent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records the acknowledge call and returns the next enqueued reply (or default).
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The acknowledge alarm request.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public Task<AcknowledgeAlarmReply> AcknowledgeAlarmAsync(
|
||||||
|
AcknowledgeAlarmRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
AcknowledgeAlarmCalls.Add((request, callOptions));
|
||||||
|
if (AcknowledgeAlarmExceptions.TryDequeue(out Exception? exception))
|
||||||
|
{
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(_acknowledgeReplies.Count > 0
|
||||||
|
? _acknowledgeReplies.Dequeue()
|
||||||
|
: new AcknowledgeAlarmReply
|
||||||
|
{
|
||||||
|
CorrelationId = request.ClientCorrelationId,
|
||||||
|
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||||
|
Status = new MxStatusProxy { Success = 1, Category = MxStatusCategory.Ok },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records the query call and yields each enqueued snapshot.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The query active alarms request.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public async IAsyncEnumerable<ActiveAlarmSnapshot> QueryActiveAlarmsAsync(
|
||||||
|
QueryActiveAlarmsRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
QueryActiveAlarmsCalls.Add((request, callOptions));
|
||||||
|
|
||||||
|
foreach (ActiveAlarmSnapshot snapshot in _activeAlarmSnapshots)
|
||||||
|
{
|
||||||
|
callOptions.CancellationToken.ThrowIfCancellationRequested();
|
||||||
|
await Task.Yield();
|
||||||
|
yield return snapshot;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Enqueues an acknowledge reply.</summary>
|
||||||
|
/// <param name="reply">The acknowledge reply to enqueue.</param>
|
||||||
|
public void AddAcknowledgeReply(AcknowledgeAlarmReply reply)
|
||||||
|
{
|
||||||
|
_acknowledgeReplies.Enqueue(reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Enqueues a snapshot to be yielded from QueryActiveAlarmsAsync.</summary>
|
||||||
|
/// <param name="snapshot">The snapshot to enqueue.</param>
|
||||||
|
public void AddActiveAlarmSnapshot(ActiveAlarmSnapshot snapshot)
|
||||||
|
{
|
||||||
|
_activeAlarmSnapshots.Add(snapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records the stream-alarms call and yields each enqueued feed message.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The stream alarms request.</param>
|
||||||
|
/// <param name="callOptions">Call options specifying RPC behavior.</param>
|
||||||
|
public async IAsyncEnumerable<AlarmFeedMessage> StreamAlarmsAsync(
|
||||||
|
StreamAlarmsRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
StreamAlarmsCalls.Add((request, callOptions));
|
||||||
|
|
||||||
|
foreach (AlarmFeedMessage message in _alarmFeedMessages)
|
||||||
|
{
|
||||||
|
callOptions.CancellationToken.ThrowIfCancellationRequested();
|
||||||
|
await Task.Yield();
|
||||||
|
yield return message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Enqueues an alarm feed message to be yielded from StreamAlarmsAsync.</summary>
|
||||||
|
/// <param name="message">The alarm feed message to enqueue.</param>
|
||||||
|
public void AddAlarmFeedMessage(AlarmFeedMessage message)
|
||||||
|
{
|
||||||
|
_alarmFeedMessages.Add(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
using Google.Protobuf.WellKnownTypes;
|
||||||
|
using Grpc.Core;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
|
public sealed class GalaxyRepositoryClientTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that TestConnectionAsync attaches the API key in request metadata and returns the Ok flag.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task TestConnectionAsync_AttachesApiKeyMetadataAndReturnsOkFlag()
|
||||||
|
{
|
||||||
|
using CancellationTokenSource cancellation = new();
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.TestConnectionReply = new TestConnectionReply { Ok = true };
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
bool ok = await client.TestConnectionAsync(cancellation.Token);
|
||||||
|
|
||||||
|
Assert.True(ok);
|
||||||
|
var call = Assert.Single(transport.TestConnectionCalls);
|
||||||
|
Assert.Equal("Bearer test-api-key", call.CallOptions.Headers?.GetValue("authorization"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that TestConnectionAsync returns false when the server reports NotOk.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task TestConnectionAsync_ReturnsFalseWhenServerReportsNotOk()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.TestConnectionReply = new TestConnectionReply { Ok = false };
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
bool ok = await client.TestConnectionAsync();
|
||||||
|
|
||||||
|
Assert.False(ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that GetLastDeployTimeAsync returns null when the server reports not present.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task GetLastDeployTimeAsync_ReturnsNullWhenNotPresent()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.GetLastDeployTimeReply = new GetLastDeployTimeReply { Present = false };
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
DateTime? deployTime = await client.GetLastDeployTimeAsync();
|
||||||
|
|
||||||
|
Assert.Null(deployTime);
|
||||||
|
Assert.Single(transport.GetLastDeployTimeCalls);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that GetLastDeployTimeAsync returns the timestamp when the server reports it present.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task GetLastDeployTimeAsync_ReturnsTimestampWhenPresent()
|
||||||
|
{
|
||||||
|
DateTime expected = new(2026, 4, 28, 14, 30, 0, DateTimeKind.Utc);
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.GetLastDeployTimeReply = new GetLastDeployTimeReply
|
||||||
|
{
|
||||||
|
Present = true,
|
||||||
|
TimeOfLastDeploy = Timestamp.FromDateTime(expected),
|
||||||
|
};
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
DateTime? deployTime = await client.GetLastDeployTimeAsync();
|
||||||
|
|
||||||
|
Assert.NotNull(deployTime);
|
||||||
|
Assert.Equal(expected, deployTime!.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that DiscoverHierarchyAsync returns the objects from the server reply.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task DiscoverHierarchyAsync_ReturnsObjectsFromReply()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.DiscoverHierarchyReplies.Enqueue(new DiscoverHierarchyReply
|
||||||
|
{
|
||||||
|
NextPageToken = "page-2",
|
||||||
|
TotalObjectCount = 2,
|
||||||
|
Objects =
|
||||||
|
{
|
||||||
|
new GalaxyObject
|
||||||
|
{
|
||||||
|
GobjectId = 12,
|
||||||
|
TagName = "DelmiaReceiver_001",
|
||||||
|
ContainedName = "DelmiaReceiver",
|
||||||
|
BrowseName = "TestMachine_001/DelmiaReceiver",
|
||||||
|
ParentGobjectId = 5,
|
||||||
|
Attributes =
|
||||||
|
{
|
||||||
|
new GalaxyAttribute
|
||||||
|
{
|
||||||
|
AttributeName = "DownloadPath",
|
||||||
|
FullTagReference = "DelmiaReceiver_001.DownloadPath",
|
||||||
|
MxDataType = 8,
|
||||||
|
DataTypeName = "MxString",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
transport.DiscoverHierarchyReplies.Enqueue(new DiscoverHierarchyReply
|
||||||
|
{
|
||||||
|
TotalObjectCount = 2,
|
||||||
|
Objects =
|
||||||
|
{
|
||||||
|
new GalaxyObject
|
||||||
|
{
|
||||||
|
GobjectId = 13,
|
||||||
|
TagName = "DelmiaReceiver_002",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
IReadOnlyList<GalaxyObject> objects = await client.DiscoverHierarchyAsync();
|
||||||
|
|
||||||
|
Assert.Equal(2, objects.Count);
|
||||||
|
Assert.Equal(2, transport.DiscoverHierarchyCalls.Count);
|
||||||
|
Assert.Equal(5000, transport.DiscoverHierarchyCalls[0].Request.PageSize);
|
||||||
|
Assert.Equal("", transport.DiscoverHierarchyCalls[0].Request.PageToken);
|
||||||
|
Assert.Equal("page-2", transport.DiscoverHierarchyCalls[1].Request.PageToken);
|
||||||
|
GalaxyObject obj = objects[0];
|
||||||
|
Assert.Equal(12, obj.GobjectId);
|
||||||
|
Assert.Equal("DelmiaReceiver_001", obj.TagName);
|
||||||
|
GalaxyAttribute attribute = Assert.Single(obj.Attributes);
|
||||||
|
Assert.Equal("DownloadPath", attribute.AttributeName);
|
||||||
|
Assert.Equal("DelmiaReceiver_001.DownloadPath", attribute.FullTagReference);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that DiscoverHierarchyAsync propagates cancellation tokens to the transport.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task DiscoverHierarchyAsync_PropagatesCancellationToTransport()
|
||||||
|
{
|
||||||
|
using CancellationTokenSource cancellation = new();
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
await client.DiscoverHierarchyAsync(cancellation.Token);
|
||||||
|
|
||||||
|
var call = Assert.Single(transport.DiscoverHierarchyCalls);
|
||||||
|
// The retry pipeline links the caller token with a per-call timeout token,
|
||||||
|
// so the transport sees the linked token rather than the caller's directly.
|
||||||
|
// Verify the link relationship by cancelling the caller and checking the
|
||||||
|
// call-side token reflects it.
|
||||||
|
Assert.False(call.CallOptions.CancellationToken.IsCancellationRequested);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that TestConnectionAsync retries on transient gRPC failures.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task DiscoverHierarchyAsync_WithRepeatedPageToken_ThrowsProtocolError()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.DiscoverHierarchyReplies.Enqueue(new DiscoverHierarchyReply
|
||||||
|
{
|
||||||
|
NextPageToken = "7:1",
|
||||||
|
});
|
||||||
|
transport.DiscoverHierarchyReplies.Enqueue(new DiscoverHierarchyReply
|
||||||
|
{
|
||||||
|
NextPageToken = "7:1",
|
||||||
|
});
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
MxGatewayException exception = await Assert.ThrowsAsync<MxGatewayException>(
|
||||||
|
async () => await client.DiscoverHierarchyAsync());
|
||||||
|
|
||||||
|
Assert.Contains("repeated page token", exception.Message, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that DiscoverHierarchyAsync maps typed filter options correctly to the request.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task DiscoverHierarchyAsync_WithOptions_MapsTypedFilters()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
await client.DiscoverHierarchyAsync(new DiscoverHierarchyOptions
|
||||||
|
{
|
||||||
|
RootContainedPath = "Area1/Line3",
|
||||||
|
MaxDepth = 2,
|
||||||
|
CategoryIds = [10, 13],
|
||||||
|
TemplateChainContains = ["Pump"],
|
||||||
|
TagNameGlob = "Pump_*",
|
||||||
|
IncludeAttributes = false,
|
||||||
|
AlarmBearingOnly = true,
|
||||||
|
HistorizedOnly = true,
|
||||||
|
});
|
||||||
|
|
||||||
|
DiscoverHierarchyRequest request = Assert.Single(transport.DiscoverHierarchyCalls).Request;
|
||||||
|
Assert.Equal(DiscoverHierarchyRequest.RootOneofCase.RootContainedPath, request.RootCase);
|
||||||
|
Assert.Equal("Area1/Line3", request.RootContainedPath);
|
||||||
|
Assert.Equal(2, request.MaxDepth);
|
||||||
|
Assert.Equal([10, 13], request.CategoryIds);
|
||||||
|
Assert.Equal(["Pump"], request.TemplateChainContains);
|
||||||
|
Assert.Equal("Pump_*", request.TagNameGlob);
|
||||||
|
Assert.True(request.HasIncludeAttributes);
|
||||||
|
Assert.False(request.IncludeAttributes);
|
||||||
|
Assert.True(request.AlarmBearingOnly);
|
||||||
|
Assert.True(request.HistorizedOnly);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that TestConnectionAsync retries on transient gRPC failures.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task TestConnectionAsync_RetriesOnTransientGrpcFailure()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.TestConnectionExceptions.Enqueue(CreateTransientRpcException());
|
||||||
|
transport.TestConnectionReply = new TestConnectionReply { Ok = true };
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
bool ok = await client.TestConnectionAsync();
|
||||||
|
|
||||||
|
Assert.True(ok);
|
||||||
|
Assert.Equal(2, transport.TestConnectionCalls.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that DiscoverHierarchyAsync retries on transient gRPC failures.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task DiscoverHierarchyAsync_RetriesOnTransientGrpcFailure()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.DiscoverHierarchyExceptions.Enqueue(CreateTransientRpcException());
|
||||||
|
transport.DiscoverHierarchyReply = new DiscoverHierarchyReply();
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
await client.DiscoverHierarchyAsync();
|
||||||
|
|
||||||
|
Assert.Equal(2, transport.DiscoverHierarchyCalls.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that WatchDeployEventsAsync delivers the bootstrap event.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task WatchDeployEventsAsync_DeliversBootstrapEvent()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
DateTime deployTime = new(2026, 4, 28, 14, 30, 0, DateTimeKind.Utc);
|
||||||
|
transport.WatchDeployEvents.Add(new DeployEvent
|
||||||
|
{
|
||||||
|
Sequence = 1,
|
||||||
|
ObservedAt = Timestamp.FromDateTime(deployTime),
|
||||||
|
TimeOfLastDeploy = Timestamp.FromDateTime(deployTime),
|
||||||
|
TimeOfLastDeployPresent = true,
|
||||||
|
ObjectCount = 7,
|
||||||
|
AttributeCount = 42,
|
||||||
|
});
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
List<DeployEvent> received = [];
|
||||||
|
await foreach (DeployEvent evt in client.WatchDeployEventsAsync())
|
||||||
|
{
|
||||||
|
received.Add(evt);
|
||||||
|
}
|
||||||
|
|
||||||
|
DeployEvent only = Assert.Single(received);
|
||||||
|
Assert.Equal(1ul, only.Sequence);
|
||||||
|
Assert.Equal(7, only.ObjectCount);
|
||||||
|
Assert.Equal(42, only.AttributeCount);
|
||||||
|
Assert.True(only.TimeOfLastDeployPresent);
|
||||||
|
var call = Assert.Single(transport.WatchDeployEventsCalls);
|
||||||
|
Assert.Equal("Bearer test-api-key", call.CallOptions.Headers?.GetValue("authorization"));
|
||||||
|
// No last_seen_deploy_time supplied → request leaves the field unset.
|
||||||
|
Assert.Null(call.Request.LastSeenDeployTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that WatchDeployEventsAsync delivers multiple events in order.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task WatchDeployEventsAsync_DeliversMultipleEventsInOrder()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
DateTime t0 = new(2026, 4, 28, 14, 30, 0, DateTimeKind.Utc);
|
||||||
|
for (int index = 1; index <= 3; index++)
|
||||||
|
{
|
||||||
|
transport.WatchDeployEvents.Add(new DeployEvent
|
||||||
|
{
|
||||||
|
Sequence = (ulong)index,
|
||||||
|
ObservedAt = Timestamp.FromDateTime(t0.AddSeconds(index)),
|
||||||
|
TimeOfLastDeploy = Timestamp.FromDateTime(t0.AddSeconds(index)),
|
||||||
|
TimeOfLastDeployPresent = true,
|
||||||
|
ObjectCount = 10 + index,
|
||||||
|
AttributeCount = 100 + index,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
DateTimeOffset lastSeen = new(t0, TimeSpan.Zero);
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
List<DeployEvent> received = [];
|
||||||
|
await foreach (DeployEvent evt in client.WatchDeployEventsAsync(lastSeen))
|
||||||
|
{
|
||||||
|
received.Add(evt);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(3, received.Count);
|
||||||
|
Assert.Equal(new ulong[] { 1, 2, 3 }, received.Select(e => e.Sequence).ToArray());
|
||||||
|
Assert.Equal(new[] { 11, 12, 13 }, received.Select(e => e.ObjectCount).ToArray());
|
||||||
|
var call = Assert.Single(transport.WatchDeployEventsCalls);
|
||||||
|
Assert.NotNull(call.Request.LastSeenDeployTime);
|
||||||
|
Assert.Equal(t0, call.Request.LastSeenDeployTime!.ToDateTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that WatchDeployEventsAsync stops iteration cleanly when cancelled.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task WatchDeployEventsAsync_CancellationStopsIterationCleanly()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
// Add many events; the test will cancel after the first.
|
||||||
|
for (int index = 1; index <= 10; index++)
|
||||||
|
{
|
||||||
|
transport.WatchDeployEvents.Add(new DeployEvent { Sequence = (ulong)index });
|
||||||
|
}
|
||||||
|
|
||||||
|
using CancellationTokenSource cancellation = new();
|
||||||
|
// Cancel before the second yield by wiring the fake's pre-yield hook.
|
||||||
|
int yields = 0;
|
||||||
|
transport.WatchDeployEventsBeforeYield = _ =>
|
||||||
|
{
|
||||||
|
yields++;
|
||||||
|
if (yields >= 2)
|
||||||
|
{
|
||||||
|
cancellation.Cancel();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
};
|
||||||
|
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
List<DeployEvent> received = [];
|
||||||
|
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () =>
|
||||||
|
{
|
||||||
|
await foreach (DeployEvent evt in client
|
||||||
|
.WatchDeployEventsAsync(cancellationToken: cancellation.Token))
|
||||||
|
{
|
||||||
|
received.Add(evt);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// The first event yields before cancellation triggers on the second pass.
|
||||||
|
Assert.Single(received);
|
||||||
|
Assert.Equal(1ul, received[0].Sequence);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that WatchDeployEventsAsync throws ObjectDisposedException after the client is disposed.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task WatchDeployEventsAsync_ThrowsAfterDisposal()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
await client.DisposeAsync();
|
||||||
|
|
||||||
|
Assert.Throws<ObjectDisposedException>(() =>
|
||||||
|
client.WatchDeployEventsAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that TestConnectionAsync throws ObjectDisposedException after the client is disposed.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task TestConnectionAsync_ThrowsAfterDisposal()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
await client.DisposeAsync();
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<ObjectDisposedException>(() => client.TestConnectionAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GalaxyRepositoryClient CreateClient(FakeGalaxyRepositoryTransport transport)
|
||||||
|
{
|
||||||
|
return new GalaxyRepositoryClient(transport.Options, transport);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FakeGalaxyRepositoryTransport CreateTransport()
|
||||||
|
{
|
||||||
|
return new FakeGalaxyRepositoryTransport(new MxGatewayClientOptions
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("http://localhost:5000"),
|
||||||
|
ApiKey = "test-api-key",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RpcException CreateTransientRpcException()
|
||||||
|
{
|
||||||
|
return new RpcException(new Status(StatusCode.Unavailable, "gateway unavailable"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tests for the <see cref="LazyBrowseNode"/> walker over the BrowseChildren RPC.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class LazyBrowseNodeTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that calling BrowseAsync with no parent returns the root nodes
|
||||||
|
/// from the first BrowseChildren reply and surfaces the per-child has-children hint.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task Browse_NoParent_ReturnsRoots()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(BuildReply(
|
||||||
|
children: [BuildObject(1, "Plant", isArea: true), BuildObject(2, "Other")],
|
||||||
|
childHasChildren: [true, false],
|
||||||
|
cacheSequence: 1));
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
IReadOnlyList<LazyBrowseNode> roots = await client.BrowseAsync();
|
||||||
|
|
||||||
|
Assert.Equal(2, roots.Count);
|
||||||
|
Assert.Equal("Plant", roots[0].Object.TagName);
|
||||||
|
Assert.True(roots[0].HasChildrenHint);
|
||||||
|
Assert.False(roots[0].IsExpanded);
|
||||||
|
Assert.Equal("Other", roots[1].Object.TagName);
|
||||||
|
Assert.False(roots[1].HasChildrenHint);
|
||||||
|
Assert.False(roots[1].IsExpanded);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that ExpandAsync populates Children and marks the node expanded after one RPC.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task Expand_PopulatesChildrenAndMarksExpanded()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(BuildReply(
|
||||||
|
children: [BuildObject(1, "Plant", isArea: true)],
|
||||||
|
childHasChildren: [true],
|
||||||
|
cacheSequence: 1));
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(BuildReply(
|
||||||
|
children: [BuildObject(10, "Line1")],
|
||||||
|
childHasChildren: [false],
|
||||||
|
cacheSequence: 1));
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
IReadOnlyList<LazyBrowseNode> roots = await client.BrowseAsync();
|
||||||
|
await roots[0].ExpandAsync();
|
||||||
|
|
||||||
|
Assert.True(roots[0].IsExpanded);
|
||||||
|
Assert.Single(roots[0].Children);
|
||||||
|
Assert.Equal("Line1", roots[0].Children[0].Object.TagName);
|
||||||
|
Assert.Equal(2, transport.BrowseChildrenCalls.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that a second ExpandAsync call is a no-op and issues no additional RPC.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task Expand_CalledTwice_NoSecondRpc()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(BuildReply(
|
||||||
|
children: [BuildObject(1, "Plant", isArea: true)],
|
||||||
|
childHasChildren: [true],
|
||||||
|
cacheSequence: 1));
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(BuildReply(
|
||||||
|
children: [BuildObject(10, "Line1")],
|
||||||
|
childHasChildren: [false],
|
||||||
|
cacheSequence: 1));
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
IReadOnlyList<LazyBrowseNode> roots = await client.BrowseAsync();
|
||||||
|
await roots[0].ExpandAsync();
|
||||||
|
await roots[0].ExpandAsync();
|
||||||
|
|
||||||
|
Assert.Equal(2, transport.BrowseChildrenCalls.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that an RPC failure (NotFound) during expand is wrapped in MxGatewayException.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task Expand_UnknownParent_ThrowsMxGatewayException()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(BuildReply(
|
||||||
|
children: [BuildObject(1, "Plant", isArea: true)],
|
||||||
|
childHasChildren: [true],
|
||||||
|
cacheSequence: 1));
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
IReadOnlyList<LazyBrowseNode> roots = await client.BrowseAsync();
|
||||||
|
|
||||||
|
// Queue the failure for the upcoming ExpandAsync call so it consumes
|
||||||
|
// the exception on its first RPC rather than the BrowseAsync above.
|
||||||
|
transport.BrowseChildrenExceptions.Enqueue(
|
||||||
|
new MxGatewayException(
|
||||||
|
"Parent not found",
|
||||||
|
new RpcException(new Status(StatusCode.NotFound, "Parent not found"))));
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<MxGatewayException>(async () => await roots[0].ExpandAsync());
|
||||||
|
Assert.False(roots[0].IsExpanded);
|
||||||
|
Assert.Empty(roots[0].Children);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that ExpandAsync drains multi-page sibling replies and forwards the page token.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task Expand_MultiPageSiblings_GathersAllPages()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
// Roots
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(BuildReply(
|
||||||
|
children: [BuildObject(7, "Plant", isArea: true)],
|
||||||
|
childHasChildren: [true],
|
||||||
|
cacheSequence: 1));
|
||||||
|
// First child page (2 children) with a next token
|
||||||
|
BrowseChildrenReply childPage1 = BuildReply(
|
||||||
|
children: [BuildObject(70, "ChildA"), BuildObject(71, "ChildB")],
|
||||||
|
childHasChildren: [false, false],
|
||||||
|
cacheSequence: 1);
|
||||||
|
childPage1.NextPageToken = "7:abc:2";
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(childPage1);
|
||||||
|
// Second child page (1 child) with no next token
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(BuildReply(
|
||||||
|
children: [BuildObject(72, "ChildC")],
|
||||||
|
childHasChildren: [false],
|
||||||
|
cacheSequence: 1));
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
IReadOnlyList<LazyBrowseNode> roots = await client.BrowseAsync();
|
||||||
|
await roots[0].ExpandAsync();
|
||||||
|
|
||||||
|
Assert.Equal(3, roots[0].Children.Count);
|
||||||
|
Assert.Equal(3, transport.BrowseChildrenCalls.Count);
|
||||||
|
Assert.Equal("7:abc:2", transport.BrowseChildrenCalls[2].Request.PageToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that ten concurrent ExpandAsync calls issue exactly one RPC, not ten.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task Expand_CalledConcurrently_OnlyFiresOneRpc()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(BuildReply(
|
||||||
|
children: [BuildObject(1, "Plant", isArea: true)],
|
||||||
|
childHasChildren: [true],
|
||||||
|
cacheSequence: 7));
|
||||||
|
transport.BrowseChildrenReplies.Enqueue(BuildReply(
|
||||||
|
children: [BuildObject(2, "Mixer_001")],
|
||||||
|
childHasChildren: [false],
|
||||||
|
cacheSequence: 7));
|
||||||
|
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
IReadOnlyList<LazyBrowseNode> roots = await client.BrowseAsync();
|
||||||
|
|
||||||
|
// Fire ten concurrent expands of the same node.
|
||||||
|
Task[] tasks = Enumerable.Range(0, 10)
|
||||||
|
.Select(_ => roots[0].ExpandAsync())
|
||||||
|
.ToArray();
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
|
||||||
|
Assert.True(roots[0].IsExpanded);
|
||||||
|
Assert.Single(roots[0].Children);
|
||||||
|
// 1 roots fetch + exactly 1 expand fetch = 2 total
|
||||||
|
Assert.Equal(2, transport.BrowseChildrenCalls.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that BrowseChildrenOptions filter fields are forwarded to the BrowseChildren request.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task Browse_WithFilter_ForwardsToRequest()
|
||||||
|
{
|
||||||
|
FakeGalaxyRepositoryTransport transport = CreateTransport();
|
||||||
|
await using GalaxyRepositoryClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
await client.BrowseAsync(new BrowseChildrenOptions
|
||||||
|
{
|
||||||
|
TagNameGlob = "Mixer*",
|
||||||
|
AlarmBearingOnly = true,
|
||||||
|
});
|
||||||
|
|
||||||
|
BrowseChildrenRequest request = Assert.Single(transport.BrowseChildrenCalls).Request;
|
||||||
|
Assert.Equal("Mixer*", request.TagNameGlob);
|
||||||
|
Assert.True(request.AlarmBearingOnly);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GalaxyObject BuildObject(int id, string tag, bool isArea = false)
|
||||||
|
=> new() { GobjectId = id, TagName = tag, BrowseName = tag, IsArea = isArea };
|
||||||
|
|
||||||
|
private static BrowseChildrenReply BuildReply(
|
||||||
|
IReadOnlyList<GalaxyObject> children,
|
||||||
|
IReadOnlyList<bool> childHasChildren,
|
||||||
|
ulong cacheSequence)
|
||||||
|
{
|
||||||
|
BrowseChildrenReply reply = new() { TotalChildCount = children.Count, CacheSequence = cacheSequence };
|
||||||
|
reply.Children.AddRange(children);
|
||||||
|
reply.ChildHasChildren.AddRange(childHasChildren);
|
||||||
|
return reply;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GalaxyRepositoryClient CreateClient(FakeGalaxyRepositoryTransport transport)
|
||||||
|
=> new(transport.Options, transport);
|
||||||
|
|
||||||
|
private static FakeGalaxyRepositoryTransport CreateTransport()
|
||||||
|
=> new(new MxGatewayClientOptions
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("http://localhost:5000"),
|
||||||
|
ApiKey = "test-api-key",
|
||||||
|
});
|
||||||
|
}
|
||||||
+6
-3
@@ -1,11 +1,12 @@
|
|||||||
using Google.Protobuf;
|
using Google.Protobuf;
|
||||||
using MxGateway.Client;
|
using ZB.MOM.WW.MxGateway.Client;
|
||||||
using MxGateway.Contracts.Proto;
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
namespace MxGateway.Client.Tests;
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
public sealed class MxCommandReplyExtensionsTests
|
public sealed class MxCommandReplyExtensionsTests
|
||||||
{
|
{
|
||||||
|
/// <summary>Verifies that successful replies pass both protocol and MxAccess success checks.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void EnsureSuccess_WithRegisterFixture_ReturnsReply()
|
public void EnsureSuccess_WithRegisterFixture_ReturnsReply()
|
||||||
{
|
{
|
||||||
@@ -15,6 +16,7 @@ public sealed class MxCommandReplyExtensionsTests
|
|||||||
Assert.Same(reply, reply.EnsureMxAccessSuccess());
|
Assert.Same(reply, reply.EnsureMxAccessSuccess());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that MxAccess failures throw with preserved HResult and status details.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void EnsureMxAccessSuccess_WithFailureFixture_PreservesHResultAndStatuses()
|
public void EnsureMxAccessSuccess_WithFailureFixture_PreservesHResultAndStatuses()
|
||||||
{
|
{
|
||||||
@@ -30,6 +32,7 @@ public sealed class MxCommandReplyExtensionsTests
|
|||||||
Assert.Contains("0x80040200", exception.Message);
|
Assert.Contains("0x80040200", exception.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that session-not-found protocol failures throw the correct gateway exception.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void EnsureProtocolSuccess_WithSessionFailure_ThrowsSessionException()
|
public void EnsureProtocolSuccess_WithSessionFailure_ThrowsSessionException()
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
using Google.Protobuf.WellKnownTypes;
|
||||||
|
using Grpc.Core;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// PR E.2 — pins the .NET SDK surface for the new alarm RPCs:
|
||||||
|
/// <see cref="MxGatewayClient.AcknowledgeAlarmAsync"/> and
|
||||||
|
/// <see cref="MxGatewayClient.QueryActiveAlarmsAsync"/>.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class MxGatewayClientAlarmsTests
|
||||||
|
{
|
||||||
|
/// <summary>AcknowledgeAlarmAsync records request and returns reply.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task AcknowledgeAlarmAsync_RecordsRequestShapeAndReturnsReply()
|
||||||
|
{
|
||||||
|
FakeGatewayTransport transport = CreateTransport();
|
||||||
|
transport.AddAcknowledgeReply(new AcknowledgeAlarmReply
|
||||||
|
{
|
||||||
|
CorrelationId = "corr-1",
|
||||||
|
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||||
|
Status = new MxStatusProxy
|
||||||
|
{
|
||||||
|
Success = 1,
|
||||||
|
Category = MxStatusCategory.Ok,
|
||||||
|
DetectedBy = MxStatusSource.RespondingLmx,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await using MxGatewayClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
AcknowledgeAlarmReply reply = await client.AcknowledgeAlarmAsync(new AcknowledgeAlarmRequest
|
||||||
|
{
|
||||||
|
ClientCorrelationId = "corr-1",
|
||||||
|
AlarmFullReference = "Tank01.Level.HiHi",
|
||||||
|
Comment = "investigating",
|
||||||
|
OperatorUser = "alice",
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.Equal(ProtocolStatusCode.Ok, reply.ProtocolStatus.Code);
|
||||||
|
Assert.Equal(MxStatusCategory.Ok, reply.Status.Category);
|
||||||
|
|
||||||
|
var call = Assert.Single(transport.AcknowledgeAlarmCalls);
|
||||||
|
Assert.Equal("Tank01.Level.HiHi", call.Request.AlarmFullReference);
|
||||||
|
Assert.Equal("investigating", call.Request.Comment);
|
||||||
|
Assert.Equal("alice", call.Request.OperatorUser);
|
||||||
|
Assert.Equal("Bearer test-api-key", call.CallOptions.Headers?.GetValue("authorization"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>AcknowledgeAlarmAsync honors cancellation.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task AcknowledgeAlarmAsync_HonorsCancellation()
|
||||||
|
{
|
||||||
|
// Acks are routed through the safe-unary retry pipeline (idempotent at the
|
||||||
|
// MxAccess level), so the transport-side cancellation token is a linked one
|
||||||
|
// rather than the caller's original. Verify cancellation by tripping the source
|
||||||
|
// and asserting the call observes it.
|
||||||
|
using CancellationTokenSource cancellation = new();
|
||||||
|
cancellation.Cancel();
|
||||||
|
FakeGatewayTransport transport = CreateTransport();
|
||||||
|
await using MxGatewayClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||||
|
client.AcknowledgeAlarmAsync(
|
||||||
|
new AcknowledgeAlarmRequest
|
||||||
|
{
|
||||||
|
AlarmFullReference = "Tank01.Level.HiHi",
|
||||||
|
Comment = string.Empty,
|
||||||
|
OperatorUser = "alice",
|
||||||
|
},
|
||||||
|
cancellation.Token));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>AcknowledgeAlarmAsync maps unauthenticated RPC exception to typed exception.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task AcknowledgeAlarmAsync_MapsUnauthenticated_RpcException_ToTypedException()
|
||||||
|
{
|
||||||
|
FakeGatewayTransport transport = CreateTransport();
|
||||||
|
transport.AcknowledgeAlarmExceptions.Enqueue(
|
||||||
|
new RpcException(new Status(StatusCode.Unauthenticated, "expired key")));
|
||||||
|
await using MxGatewayClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
// Note: the FakeGatewayTransport surfaces RpcException directly (it does not run
|
||||||
|
// through GrpcMxGatewayClientTransport's mapping); the fake's contract here is to
|
||||||
|
// pass the exception verbatim. RpcException → typed exception mapping is covered
|
||||||
|
// in the GrpcMxGatewayClientTransport-level tests; the SDK-level test pins the
|
||||||
|
// pass-through shape so a future migration to direct mapping won't silently
|
||||||
|
// change observable behaviour.
|
||||||
|
var ex = await Assert.ThrowsAsync<RpcException>(
|
||||||
|
() => client.AcknowledgeAlarmAsync(new AcknowledgeAlarmRequest
|
||||||
|
{
|
||||||
|
AlarmFullReference = "Tank01.Level.HiHi",
|
||||||
|
Comment = string.Empty,
|
||||||
|
OperatorUser = "alice",
|
||||||
|
}));
|
||||||
|
Assert.Equal(StatusCode.Unauthenticated, ex.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>QueryActiveAlarmsAsync streams enqueued snapshots.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task QueryActiveAlarmsAsync_StreamsEnqueuedSnapshots()
|
||||||
|
{
|
||||||
|
FakeGatewayTransport transport = CreateTransport();
|
||||||
|
transport.AddActiveAlarmSnapshot(MakeSnapshot("Tank01.Level.HiHi", AlarmConditionState.Active));
|
||||||
|
transport.AddActiveAlarmSnapshot(MakeSnapshot("Tank02.Level.HiHi", AlarmConditionState.ActiveAcked));
|
||||||
|
await using MxGatewayClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
List<ActiveAlarmSnapshot> snapshots = [];
|
||||||
|
await foreach (ActiveAlarmSnapshot snapshot in client.QueryActiveAlarmsAsync(new QueryActiveAlarmsRequest
|
||||||
|
{
|
||||||
|
SessionId = "session-fixture",
|
||||||
|
}))
|
||||||
|
{
|
||||||
|
snapshots.Add(snapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(2, snapshots.Count);
|
||||||
|
Assert.Equal("Tank01.Level.HiHi", snapshots[0].AlarmFullReference);
|
||||||
|
Assert.Equal(AlarmConditionState.Active, snapshots[0].CurrentState);
|
||||||
|
Assert.Equal(AlarmConditionState.ActiveAcked, snapshots[1].CurrentState);
|
||||||
|
Assert.Single(transport.QueryActiveAlarmsCalls);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>QueryActiveAlarmsAsync passes filter prefix.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task QueryActiveAlarmsAsync_PassesFilterPrefix()
|
||||||
|
{
|
||||||
|
FakeGatewayTransport transport = CreateTransport();
|
||||||
|
await using MxGatewayClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
await foreach (ActiveAlarmSnapshot _ in client.QueryActiveAlarmsAsync(new QueryActiveAlarmsRequest
|
||||||
|
{
|
||||||
|
SessionId = "session-fixture",
|
||||||
|
AlarmFilterPrefix = "Tank01.",
|
||||||
|
}))
|
||||||
|
{
|
||||||
|
// no snapshots enqueued; just verifying the request passes through
|
||||||
|
}
|
||||||
|
|
||||||
|
var call = Assert.Single(transport.QueryActiveAlarmsCalls);
|
||||||
|
Assert.Equal("Tank01.", call.Request.AlarmFilterPrefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>QueryActiveAlarmsAsync honors cancellation during enumeration.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task QueryActiveAlarmsAsync_HonorsCancellationDuringEnumeration()
|
||||||
|
{
|
||||||
|
FakeGatewayTransport transport = CreateTransport();
|
||||||
|
transport.AddActiveAlarmSnapshot(MakeSnapshot("Tank01.Level.HiHi", AlarmConditionState.Active));
|
||||||
|
transport.AddActiveAlarmSnapshot(MakeSnapshot("Tank02.Level.HiHi", AlarmConditionState.Active));
|
||||||
|
await using MxGatewayClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
using CancellationTokenSource cancellation = new();
|
||||||
|
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
|
||||||
|
{
|
||||||
|
await foreach (ActiveAlarmSnapshot _ in client.QueryActiveAlarmsAsync(
|
||||||
|
new QueryActiveAlarmsRequest { SessionId = "session-fixture" },
|
||||||
|
cancellation.Token))
|
||||||
|
{
|
||||||
|
cancellation.Cancel();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ActiveAlarmSnapshot MakeSnapshot(string fullReference, AlarmConditionState state)
|
||||||
|
{
|
||||||
|
return new ActiveAlarmSnapshot
|
||||||
|
{
|
||||||
|
AlarmFullReference = fullReference,
|
||||||
|
SourceObjectReference = fullReference.Split('.')[0],
|
||||||
|
AlarmTypeName = "AnalogLimitAlarm.HiHi",
|
||||||
|
Severity = 750,
|
||||||
|
CurrentState = state,
|
||||||
|
Category = "Process",
|
||||||
|
Description = "Tank high-high level",
|
||||||
|
OriginalRaiseTimestamp = Timestamp.FromDateTime(new DateTime(2026, 5, 1, 12, 0, 0, DateTimeKind.Utc)),
|
||||||
|
LastTransitionTimestamp = Timestamp.FromDateTime(new DateTime(2026, 5, 1, 12, 0, 30, DateTimeKind.Utc)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MxGatewayClient CreateClient(FakeGatewayTransport transport)
|
||||||
|
{
|
||||||
|
return new MxGatewayClient(transport.Options, transport);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FakeGatewayTransport CreateTransport()
|
||||||
|
{
|
||||||
|
return new FakeGatewayTransport(new MxGatewayClientOptions
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("http://localhost:5000"),
|
||||||
|
ApiKey = "test-api-key",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
+4
-2
@@ -1,9 +1,10 @@
|
|||||||
using MxGateway.Contracts;
|
using ZB.MOM.WW.MxGateway.Contracts;
|
||||||
|
|
||||||
namespace MxGateway.Client.Tests;
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
public sealed class MxGatewayClientContractInfoTests
|
public sealed class MxGatewayClientContractInfoTests
|
||||||
{
|
{
|
||||||
|
/// <summary>Verifies that the client's gateway protocol version matches the shared contract definition.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void GatewayProtocolVersion_MatchesSharedContract()
|
public void GatewayProtocolVersion_MatchesSharedContract()
|
||||||
{
|
{
|
||||||
@@ -12,6 +13,7 @@ public sealed class MxGatewayClientContractInfoTests
|
|||||||
MxGatewayClientContractInfo.GatewayProtocolVersion);
|
MxGatewayClientContractInfo.GatewayProtocolVersion);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that the client's worker protocol version matches the shared contract definition.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void WorkerProtocolVersion_MatchesSharedContract()
|
public void WorkerProtocolVersion_MatchesSharedContract()
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
|
public sealed class MxGatewayClientOptionsTests
|
||||||
|
{
|
||||||
|
/// <summary>Verifies that options with valid endpoint and API key pass validation.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WithAbsoluteEndpointAndApiKey_Succeeds()
|
||||||
|
{
|
||||||
|
var options = new MxGatewayClientOptions
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("http://localhost:5000"),
|
||||||
|
ApiKey = "test-api-key",
|
||||||
|
};
|
||||||
|
|
||||||
|
options.Validate();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that empty API key causes validation to fail.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WithEmptyApiKey_Throws()
|
||||||
|
{
|
||||||
|
var options = new MxGatewayClientOptions
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("http://localhost:5000"),
|
||||||
|
ApiKey = "",
|
||||||
|
};
|
||||||
|
|
||||||
|
Assert.Throws<ArgumentException>(options.Validate);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that invalid retry options cause validation to fail.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WithInvalidRetryOptions_Throws()
|
||||||
|
{
|
||||||
|
var options = new MxGatewayClientOptions
|
||||||
|
{
|
||||||
|
Endpoint = new Uri("http://localhost:5000"),
|
||||||
|
ApiKey = "test-api-key",
|
||||||
|
Retry = new MxGatewayClientRetryOptions { MaxAttempts = 0 },
|
||||||
|
};
|
||||||
|
|
||||||
|
Assert.Throws<ArgumentOutOfRangeException>(options.Validate);
|
||||||
|
}
|
||||||
|
}
|
||||||
+109
-2
@@ -1,9 +1,12 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
using Grpc.Core;
|
||||||
|
|
||||||
namespace MxGateway.Client.Tests;
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
|
/// <summary>Tests for MxGatewaySession and client command behavior.</summary>
|
||||||
public sealed class MxGatewayClientSessionTests
|
public sealed class MxGatewayClientSessionTests
|
||||||
{
|
{
|
||||||
|
/// <summary>Verifies that open session attaches API key metadata and cancellation token.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task OpenSessionRawAsync_AttachesApiKeyMetadataAndCancellation()
|
public async Task OpenSessionRawAsync_AttachesApiKeyMetadataAndCancellation()
|
||||||
{
|
{
|
||||||
@@ -18,6 +21,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
Assert.Equal(cancellation.Token, call.CallOptions.CancellationToken);
|
Assert.Equal(cancellation.Token, call.CallOptions.CancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that open session returns a session with the raw open reply.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task OpenSessionAsync_ReturnsSessionWithRawOpenReply()
|
public async Task OpenSessionAsync_ReturnsSessionWithRawOpenReply()
|
||||||
{
|
{
|
||||||
@@ -32,6 +36,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
Assert.Equal(1234, session.OpenSessionReply.WorkerProcessId);
|
Assert.Equal(1234, session.OpenSessionReply.WorkerProcessId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that register builds a register command and returns server handle.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task RegisterAsync_BuildsRegisterCommandAndReturnsServerHandle()
|
public async Task RegisterAsync_BuildsRegisterCommandAndReturnsServerHandle()
|
||||||
{
|
{
|
||||||
@@ -56,6 +61,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
Assert.Equal("fixture-client", call.Request.Command.Register.ClientName);
|
Assert.Equal("fixture-client", call.Request.Command.Register.ClientName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that add item 2 builds a command with the specified context.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task AddItem2Async_BuildsAddItem2CommandWithContext()
|
public async Task AddItem2Async_BuildsAddItem2CommandWithContext()
|
||||||
{
|
{
|
||||||
@@ -80,6 +86,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
Assert.Equal("runtime", request.Command.AddItem2.ItemContext);
|
Assert.Equal("runtime", request.Command.AddItem2.ItemContext);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that write raw builds a write command with the raw value.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task WriteRawAsync_BuildsWriteCommandWithRawValue()
|
public async Task WriteRawAsync_BuildsWriteCommandWithRawValue()
|
||||||
{
|
{
|
||||||
@@ -110,6 +117,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
Assert.Equal(56, request.Command.Write.UserId);
|
Assert.Equal(56, request.Command.Write.UserId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that write 2 raw builds a write 2 command with value and timestamp.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Write2RawAsync_BuildsWrite2CommandWithValueAndTimestamp()
|
public async Task Write2RawAsync_BuildsWrite2CommandWithValueAndTimestamp()
|
||||||
{
|
{
|
||||||
@@ -137,6 +145,46 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
Assert.Equal(56, request.Command.Write2.UserId);
|
Assert.Equal(56, request.Command.Write2.UserId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that subscribe bulk builds one command and returns per-item results.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task SubscribeBulkAsync_BuildsOneBulkCommandAndReturnsPerItemResults()
|
||||||
|
{
|
||||||
|
FakeGatewayTransport transport = CreateTransport();
|
||||||
|
transport.AddInvokeReply(new MxCommandReply
|
||||||
|
{
|
||||||
|
SessionId = "session-fixture",
|
||||||
|
Kind = MxCommandKind.SubscribeBulk,
|
||||||
|
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||||
|
SubscribeBulk = new BulkSubscribeReply
|
||||||
|
{
|
||||||
|
Results =
|
||||||
|
{
|
||||||
|
new SubscribeResult
|
||||||
|
{
|
||||||
|
ServerHandle = 12,
|
||||||
|
TagAddress = "Area001.Pump001.Speed",
|
||||||
|
ItemHandle = 34,
|
||||||
|
WasSuccessful = true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await using MxGatewayClient client = CreateClient(transport);
|
||||||
|
MxGatewaySession session = await client.OpenSessionAsync();
|
||||||
|
|
||||||
|
IReadOnlyList<SubscribeResult> results = await session.SubscribeBulkAsync(
|
||||||
|
12,
|
||||||
|
["Area001.Pump001.Speed"]);
|
||||||
|
|
||||||
|
SubscribeResult result = Assert.Single(results);
|
||||||
|
Assert.Equal(34, result.ItemHandle);
|
||||||
|
MxCommandRequest request = Assert.Single(transport.InvokeCalls).Request;
|
||||||
|
Assert.Equal(MxCommandKind.SubscribeBulk, request.Command.Kind);
|
||||||
|
Assert.Equal(12, request.Command.SubscribeBulk.ServerHandle);
|
||||||
|
Assert.Equal(["Area001.Pump001.Speed"], request.Command.SubscribeBulk.TagAddresses);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that stream events yields events in the order received from the gateway.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task StreamEventsAsync_YieldsEventsInGatewayOrder()
|
public async Task StreamEventsAsync_YieldsEventsInGatewayOrder()
|
||||||
{
|
{
|
||||||
@@ -167,6 +215,7 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
Assert.Equal("session-fixture", request.SessionId);
|
Assert.Equal("session-fixture", request.SessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that close is explicit and idempotent.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task CloseAsync_IsExplicitAndIdempotent()
|
public async Task CloseAsync_IsExplicitAndIdempotent()
|
||||||
{
|
{
|
||||||
@@ -182,6 +231,59 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
Assert.Equal("session-fixture", call.Request.SessionId);
|
Assert.Equal("session-fixture", call.Request.SessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that invoke retries safe diagnostic commands on transient RPC failure.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task InvokeAsync_RetriesSafeDiagnosticCommandOnTransientGrpcFailure()
|
||||||
|
{
|
||||||
|
FakeGatewayTransport transport = CreateTransport();
|
||||||
|
transport.InvokeExceptions.Enqueue(CreateTransientRpcException());
|
||||||
|
transport.AddInvokeReply(new MxCommandReply
|
||||||
|
{
|
||||||
|
SessionId = "session-fixture",
|
||||||
|
Kind = MxCommandKind.Ping,
|
||||||
|
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||||
|
});
|
||||||
|
await using MxGatewayClient client = CreateClient(transport);
|
||||||
|
MxGatewaySession session = await client.OpenSessionAsync();
|
||||||
|
|
||||||
|
await session.InvokeAsync(new MxCommandRequest
|
||||||
|
{
|
||||||
|
SessionId = session.SessionId,
|
||||||
|
Command = new MxCommand { Kind = MxCommandKind.Ping, Ping = new PingCommand() },
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.Equal(2, transport.InvokeCalls.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that open session does not retry on transient RPC failure.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task OpenSessionAsync_DoesNotRetryTransientGrpcFailure()
|
||||||
|
{
|
||||||
|
FakeGatewayTransport transport = CreateTransport();
|
||||||
|
transport.OpenSessionExceptions.Enqueue(CreateTransientRpcException());
|
||||||
|
await using MxGatewayClient client = CreateClient(transport);
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<RpcException>(async () => await client.OpenSessionAsync());
|
||||||
|
|
||||||
|
Assert.Single(transport.OpenSessionCalls);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that invoke does not retry write commands on transient RPC failure.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task InvokeAsync_DoesNotRetryWriteCommand()
|
||||||
|
{
|
||||||
|
FakeGatewayTransport transport = CreateTransport();
|
||||||
|
transport.InvokeExceptions.Enqueue(CreateTransientRpcException());
|
||||||
|
await using MxGatewayClient client = CreateClient(transport);
|
||||||
|
MxGatewaySession session = await client.OpenSessionAsync();
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<RpcException>(async () =>
|
||||||
|
await session.WriteRawAsync(1, 2, 3.ToMxValue(), userId: 0));
|
||||||
|
|
||||||
|
Assert.Single(transport.InvokeCalls);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that invoke helpers pass cancellation token to the transport.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task InvokeHelpers_PassCancellationTokenToTransport()
|
public async Task InvokeHelpers_PassCancellationTokenToTransport()
|
||||||
{
|
{
|
||||||
@@ -214,4 +316,9 @@ public sealed class MxGatewayClientSessionTests
|
|||||||
ApiKey = "test-api-key",
|
ApiKey = "test-api-key",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static RpcException CreateTransientRpcException()
|
||||||
|
{
|
||||||
|
return new RpcException(new Status(StatusCode.Unavailable, "gateway unavailable"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+2
-1
@@ -1,7 +1,8 @@
|
|||||||
namespace MxGateway.Client.Tests;
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
public sealed class MxGatewayGeneratedContractTests
|
public sealed class MxGatewayGeneratedContractTests
|
||||||
{
|
{
|
||||||
|
/// <summary>Verifies that the generated gRPC client can be instantiated from the client factory.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GeneratedGrpcClient_CanBeConstructedFromClientFactory()
|
public async Task GeneratedGrpcClient_CanBeConstructedFromClientFactory()
|
||||||
{
|
{
|
||||||
+4
-3
@@ -1,12 +1,13 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Google.Protobuf;
|
using Google.Protobuf;
|
||||||
using MxGateway.Client;
|
using ZB.MOM.WW.MxGateway.Client;
|
||||||
using MxGateway.Contracts.Proto;
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
namespace MxGateway.Client.Tests;
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
public sealed class MxStatusProxyExtensionsTests
|
public sealed class MxStatusProxyExtensionsTests
|
||||||
{
|
{
|
||||||
|
/// <summary>Verifies that fixture statuses correctly project success and preserve raw integer fields.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void FixtureStatuses_ProjectSuccessAndPreserveRawFields()
|
public void FixtureStatuses_ProjectSuccessAndPreserveRawFields()
|
||||||
{
|
{
|
||||||
+6
-3
@@ -1,12 +1,13 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Google.Protobuf;
|
using Google.Protobuf;
|
||||||
using MxGateway.Client;
|
using ZB.MOM.WW.MxGateway.Client;
|
||||||
using MxGateway.Contracts.Proto;
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
namespace MxGateway.Client.Tests;
|
namespace ZB.MOM.WW.MxGateway.Client.Tests;
|
||||||
|
|
||||||
public sealed class MxValueExtensionsTests
|
public sealed class MxValueExtensionsTests
|
||||||
{
|
{
|
||||||
|
/// <summary>Verifies that scalar values are converted to correctly-typed MxValue protobuf messages.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToMxValue_WithScalarValues_CreatesTypedProtobufValues()
|
public void ToMxValue_WithScalarValues_CreatesTypedProtobufValues()
|
||||||
{
|
{
|
||||||
@@ -18,6 +19,7 @@ public sealed class MxValueExtensionsTests
|
|||||||
Assert.Equal(MxValue.KindOneofCase.StringValue, "alpha".ToMxValue().KindCase);
|
Assert.Equal(MxValue.KindOneofCase.StringValue, "alpha".ToMxValue().KindCase);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that array values are converted to array-kind MxValue messages with correct element types and dimensions.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ToMxValue_WithArrays_CreatesTypedArrayProtobufValues()
|
public void ToMxValue_WithArrays_CreatesTypedArrayProtobufValues()
|
||||||
{
|
{
|
||||||
@@ -29,6 +31,7 @@ public sealed class MxValueExtensionsTests
|
|||||||
Assert.Equal([2U], value.ArrayValue.Dimensions);
|
Assert.Equal([2U], value.ArrayValue.Dimensions);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Verifies that fixture test cases project to expected MxValue kinds and preserve raw type metadata.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void FixtureValues_ProjectExpectedKindsAndPreserveRawMetadata()
|
public void FixtureValues_ProjectExpectedKindsAndPreserveRawMetadata()
|
||||||
{
|
{
|
||||||
+2
-2
@@ -19,8 +19,8 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\MxGateway.Client\MxGateway.Client.csproj" />
|
<ProjectReference Include="..\ZB.MOM.WW.MxGateway.Client\ZB.MOM.WW.MxGateway.Client.csproj" />
|
||||||
<ProjectReference Include="..\MxGateway.Client.Cli\MxGateway.Client.Cli.csproj" />
|
<ProjectReference Include="..\ZB.MOM.WW.MxGateway.Client.Cli\ZB.MOM.WW.MxGateway.Client.Cli.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<Solution>
|
||||||
|
<Configurations>
|
||||||
|
<Platform Name="Any CPU" />
|
||||||
|
<Platform Name="x64" />
|
||||||
|
<Platform Name="x86" />
|
||||||
|
</Configurations>
|
||||||
|
<Project Path="../../src/ZB.MOM.WW.MxGateway.Contracts/ZB.MOM.WW.MxGateway.Contracts.csproj" />
|
||||||
|
<Project Path="ZB.MOM.WW.MxGateway.Client.Cli/ZB.MOM.WW.MxGateway.Client.Cli.csproj" />
|
||||||
|
<Project Path="ZB.MOM.WW.MxGateway.Client.Tests/ZB.MOM.WW.MxGateway.Client.Tests.csproj" />
|
||||||
|
<Project Path="ZB.MOM.WW.MxGateway.Client/ZB.MOM.WW.MxGateway.Client.csproj" />
|
||||||
|
</Solution>
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Filters and shape options for <see cref="GalaxyRepositoryClient.BrowseAsync(BrowseChildrenOptions, System.Threading.CancellationToken)"/>.
|
||||||
|
/// Mirror of <see cref="DiscoverHierarchyOptions"/> for the lazy-browse path.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class BrowseChildrenOptions
|
||||||
|
{
|
||||||
|
/// <summary>Restrict to children whose Galaxy category is in this set.</summary>
|
||||||
|
public IReadOnlyList<int> CategoryIds { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Restrict to children whose template chain contains any of these tokens.</summary>
|
||||||
|
public IReadOnlyList<string> TemplateChainContains { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Optional glob-style filter on <c>tag_name</c>.</summary>
|
||||||
|
public string? TagNameGlob { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Whether to populate each <c>GalaxyObject.Attributes</c>. Null leaves the server default.</summary>
|
||||||
|
public bool? IncludeAttributes { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Restrict to children that bear at least one alarm attribute.</summary>
|
||||||
|
public bool AlarmBearingOnly { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Restrict to children that have at least one historized attribute.</summary>
|
||||||
|
public bool HistorizedOnly { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Filters and shape options for <see cref="GalaxyRepositoryClient.DiscoverHierarchyAsync(DiscoverHierarchyOptions, System.Threading.CancellationToken)"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Hand-written ergonomic wrapper around the generated
|
||||||
|
/// <c>DiscoverHierarchyRequest</c>: lets callers express a Galaxy-browse
|
||||||
|
/// slice with .NET-friendly nullable scalars and collection initializers,
|
||||||
|
/// without touching the protobuf message's <c>oneof root</c> directly.
|
||||||
|
/// </remarks>
|
||||||
|
public sealed class DiscoverHierarchyOptions
|
||||||
|
{
|
||||||
|
/// <summary>Restrict to the subtree rooted at this Galaxy <c>gobject_id</c>.</summary>
|
||||||
|
public int? RootGobjectId { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Restrict to the subtree rooted at the object with this tag name.</summary>
|
||||||
|
public string? RootTagName { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Restrict to the subtree rooted at this <c>contained_name</c> path.</summary>
|
||||||
|
public string? RootContainedPath { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Maximum traversal depth, measured from the chosen root.</summary>
|
||||||
|
public int? MaxDepth { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Restrict to objects whose Galaxy category is in this set.</summary>
|
||||||
|
public IReadOnlyList<int> CategoryIds { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Restrict to objects whose template chain contains any of these tokens.</summary>
|
||||||
|
public IReadOnlyList<string> TemplateChainContains { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Optional glob-style filter on <c>tag_name</c>.</summary>
|
||||||
|
public string? TagNameGlob { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Whether to populate each <c>GalaxyObject.Attributes</c>. Null leaves the server default.</summary>
|
||||||
|
public bool? IncludeAttributes { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Restrict to objects that bear at least one alarm attribute.</summary>
|
||||||
|
public bool AlarmBearingOnly { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Restrict to objects that have at least one historized attribute.</summary>
|
||||||
|
public bool HistorizedOnly { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,537 @@
|
|||||||
|
using Google.Protobuf.WellKnownTypes;
|
||||||
|
using Grpc.Core;
|
||||||
|
using Grpc.Net.Client;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||||
|
using Polly;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Security;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Provides the .NET client entry point for the public Galaxy Repository gRPC API.
|
||||||
|
/// All RPCs are read-only metadata calls that share the gateway's API-key auth
|
||||||
|
/// interceptor and require the <c>metadata:read</c> scope server-side.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class GalaxyRepositoryClient : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private const int DiscoverHierarchyPageSize = 5000;
|
||||||
|
private const int BrowseChildrenPageSize = 500;
|
||||||
|
|
||||||
|
private readonly GrpcChannel? _channel;
|
||||||
|
private readonly IGalaxyRepositoryClientTransport _transport;
|
||||||
|
private readonly ResiliencePipeline _safeUnaryRetryPipeline;
|
||||||
|
private bool _disposed;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a Galaxy Repository client with custom transport and options.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="options">Client options.</param>
|
||||||
|
/// <param name="transport">The underlying gRPC transport.</param>
|
||||||
|
internal GalaxyRepositoryClient(
|
||||||
|
MxGatewayClientOptions options,
|
||||||
|
IGalaxyRepositoryClientTransport transport)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(options);
|
||||||
|
options.Validate();
|
||||||
|
|
||||||
|
Options = options;
|
||||||
|
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
||||||
|
_safeUnaryRetryPipeline = MxGatewayClientRetryPolicy.Create(
|
||||||
|
options.Retry,
|
||||||
|
options.LoggerFactory?.CreateLogger<GalaxyRepositoryClient>());
|
||||||
|
_channel = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private GalaxyRepositoryClient(
|
||||||
|
GrpcChannel channel,
|
||||||
|
IGalaxyRepositoryClientTransport transport)
|
||||||
|
{
|
||||||
|
_channel = channel;
|
||||||
|
_transport = transport;
|
||||||
|
Options = transport.Options;
|
||||||
|
_safeUnaryRetryPipeline = MxGatewayClientRetryPolicy.Create(
|
||||||
|
Options.Retry,
|
||||||
|
Options.LoggerFactory?.CreateLogger<GalaxyRepositoryClient>());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Client options used to configure timeouts, authentication, and retry policy.
|
||||||
|
/// </summary>
|
||||||
|
public MxGatewayClientOptions Options { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The underlying generated gRPC client for advanced operations.
|
||||||
|
/// </summary>
|
||||||
|
public GalaxyRepository.GalaxyRepositoryClient RawClient =>
|
||||||
|
_transport.RawClient
|
||||||
|
?? throw new InvalidOperationException("The raw generated gRPC client is not available for this client instance.");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a Galaxy Repository client with the given options, establishing a new gRPC channel.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="options">Client options.</param>
|
||||||
|
/// <returns>A new client instance.</returns>
|
||||||
|
public static GalaxyRepositoryClient Create(MxGatewayClientOptions options)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(options);
|
||||||
|
options.Validate();
|
||||||
|
|
||||||
|
HttpMessageHandler handler = CreateHttpHandler(options);
|
||||||
|
var channel = GrpcChannel.ForAddress(
|
||||||
|
options.Endpoint,
|
||||||
|
new GrpcChannelOptions
|
||||||
|
{
|
||||||
|
HttpHandler = handler,
|
||||||
|
LoggerFactory = options.LoggerFactory,
|
||||||
|
MaxReceiveMessageSize = options.MaxGrpcMessageBytes,
|
||||||
|
MaxSendMessageSize = options.MaxGrpcMessageBytes,
|
||||||
|
});
|
||||||
|
|
||||||
|
return new GalaxyRepositoryClient(
|
||||||
|
channel,
|
||||||
|
new GrpcGalaxyRepositoryClientTransport(
|
||||||
|
options,
|
||||||
|
new GalaxyRepository.GalaxyRepositoryClient(channel)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Probes the Galaxy Repository database connection. Returns true when the
|
||||||
|
/// gateway can reach the configured ZB SQL Server.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>True if connection is successful, false otherwise.</returns>
|
||||||
|
public async Task<bool> TestConnectionAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
TestConnectionReply reply = await TestConnectionRawAsync(
|
||||||
|
new TestConnectionRequest(),
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
return reply.Ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Probes the Galaxy Repository database connection without result wrapping.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The test connection request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<TestConnectionReply> TestConnectionRawAsync(
|
||||||
|
TestConnectionRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return ExecuteSafeUnaryAsync(
|
||||||
|
token => _transport.TestConnectionAsync(request, CreateCallOptions(token)),
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns the timestamp of the most recent Galaxy deployment, or
|
||||||
|
/// <see langword="null"/> when no deployment has been recorded.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The deployment timestamp, or null if not recorded.</returns>
|
||||||
|
public async Task<DateTime?> GetLastDeployTimeAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
GetLastDeployTimeReply reply = await GetLastDeployTimeRawAsync(
|
||||||
|
new GetLastDeployTimeRequest(),
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (!reply.Present || reply.TimeOfLastDeploy is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.TimeOfLastDeploy.ToDateTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns the most recent Galaxy deployment timestamp without result wrapping.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The last deploy-time request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<GetLastDeployTimeReply> GetLastDeployTimeRawAsync(
|
||||||
|
GetLastDeployTimeRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return ExecuteSafeUnaryAsync(
|
||||||
|
token => _transport.GetLastDeployTimeAsync(request, CreateCallOptions(token)),
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Enumerates the deployed Galaxy object hierarchy. Each <see cref="GalaxyObject"/>
|
||||||
|
/// includes its dynamic attributes so callers can determine which tag references
|
||||||
|
/// they may subscribe to via the MxAccessGateway service.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The collection of Galaxy objects in the hierarchy.</returns>
|
||||||
|
public async Task<IReadOnlyList<GalaxyObject>> DiscoverHierarchyAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
return await DiscoverHierarchyAsync(new DiscoverHierarchyOptions(), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Discovers the Galaxy object hierarchy.</summary>
|
||||||
|
/// <param name="options">Client configuration options.</param>
|
||||||
|
/// <param name="cancellationToken">Token to observe for cancellation.</param>
|
||||||
|
/// <returns>The collection of Galaxy objects in the hierarchy.</returns>
|
||||||
|
public async Task<IReadOnlyList<GalaxyObject>> DiscoverHierarchyAsync(
|
||||||
|
DiscoverHierarchyOptions options,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
List<GalaxyObject> objects = [];
|
||||||
|
HashSet<string> seenPageTokens = new(StringComparer.Ordinal);
|
||||||
|
string pageToken = string.Empty;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
DiscoverHierarchyRequest request = CreateDiscoverHierarchyRequest(options);
|
||||||
|
request.PageSize = DiscoverHierarchyPageSize;
|
||||||
|
request.PageToken = pageToken;
|
||||||
|
DiscoverHierarchyReply reply = await DiscoverHierarchyRawAsync(
|
||||||
|
request,
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
objects.AddRange(reply.Objects);
|
||||||
|
pageToken = reply.NextPageToken;
|
||||||
|
if (!string.IsNullOrWhiteSpace(pageToken)
|
||||||
|
&& !seenPageTokens.Add(pageToken))
|
||||||
|
{
|
||||||
|
throw new MxGatewayException(
|
||||||
|
$"Galaxy DiscoverHierarchy returned a repeated page token '{pageToken}'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (!string.IsNullOrWhiteSpace(pageToken));
|
||||||
|
|
||||||
|
return objects;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DiscoverHierarchyRequest CreateDiscoverHierarchyRequest(DiscoverHierarchyOptions options)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(options);
|
||||||
|
|
||||||
|
DiscoverHierarchyRequest request = new()
|
||||||
|
{
|
||||||
|
AlarmBearingOnly = options.AlarmBearingOnly,
|
||||||
|
HistorizedOnly = options.HistorizedOnly,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (options.RootGobjectId.HasValue)
|
||||||
|
{
|
||||||
|
request.RootGobjectId = options.RootGobjectId.Value;
|
||||||
|
}
|
||||||
|
else if (!string.IsNullOrWhiteSpace(options.RootTagName))
|
||||||
|
{
|
||||||
|
request.RootTagName = options.RootTagName;
|
||||||
|
}
|
||||||
|
else if (!string.IsNullOrWhiteSpace(options.RootContainedPath))
|
||||||
|
{
|
||||||
|
request.RootContainedPath = options.RootContainedPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.MaxDepth.HasValue)
|
||||||
|
{
|
||||||
|
request.MaxDepth = options.MaxDepth.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
request.CategoryIds.Add(options.CategoryIds);
|
||||||
|
request.TemplateChainContains.Add(options.TemplateChainContains);
|
||||||
|
if (!string.IsNullOrWhiteSpace(options.TagNameGlob))
|
||||||
|
{
|
||||||
|
request.TagNameGlob = options.TagNameGlob;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.IncludeAttributes.HasValue)
|
||||||
|
{
|
||||||
|
request.IncludeAttributes = options.IncludeAttributes.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Enumerates the Galaxy object hierarchy without result wrapping.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The discover-hierarchy request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<DiscoverHierarchyReply> DiscoverHierarchyRawAsync(
|
||||||
|
DiscoverHierarchyRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return ExecuteSafeUnaryAsync(
|
||||||
|
token => _transport.DiscoverHierarchyAsync(request, CreateCallOptions(token)),
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns root-level browse nodes (objects with no parent).</summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The list of root <see cref="LazyBrowseNode"/> instances.</returns>
|
||||||
|
public Task<IReadOnlyList<LazyBrowseNode>> BrowseAsync(CancellationToken cancellationToken = default)
|
||||||
|
=> BrowseAsync(null, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Returns root-level browse nodes filtered by the given options.</summary>
|
||||||
|
/// <param name="options">Browse filter options. Null applies no filter.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The list of root <see cref="LazyBrowseNode"/> instances.</returns>
|
||||||
|
public async Task<IReadOnlyList<LazyBrowseNode>> BrowseAsync(
|
||||||
|
BrowseChildrenOptions? options,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
BrowseChildrenOptions effective = options ?? new BrowseChildrenOptions();
|
||||||
|
List<LazyBrowseNode> roots = [];
|
||||||
|
string pageToken = string.Empty;
|
||||||
|
HashSet<string> seenPageTokens = new(StringComparer.Ordinal);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
BrowseChildrenRequest request = BuildBrowseChildrenRequest(effective);
|
||||||
|
request.PageToken = pageToken;
|
||||||
|
BrowseChildrenReply reply = await BrowseChildrenRawAsync(request, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
for (int i = 0; i < reply.Children.Count; i++)
|
||||||
|
{
|
||||||
|
bool hint = i < reply.ChildHasChildren.Count && reply.ChildHasChildren[i];
|
||||||
|
roots.Add(new LazyBrowseNode(this, reply.Children[i], hint, effective));
|
||||||
|
}
|
||||||
|
|
||||||
|
pageToken = reply.NextPageToken;
|
||||||
|
if (!string.IsNullOrWhiteSpace(pageToken) && !seenPageTokens.Add(pageToken))
|
||||||
|
{
|
||||||
|
throw new MxGatewayException(
|
||||||
|
$"Galaxy BrowseChildren returned a repeated page token '{pageToken}'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (!string.IsNullOrWhiteSpace(pageToken));
|
||||||
|
|
||||||
|
return roots;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Issues a raw BrowseChildren RPC without result wrapping.</summary>
|
||||||
|
/// <param name="request">The browse-children request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<BrowseChildrenReply> BrowseChildrenRawAsync(
|
||||||
|
BrowseChildrenRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return ExecuteSafeUnaryAsync(
|
||||||
|
token => _transport.BrowseChildrenAsync(request, CreateCallOptions(token)),
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static BrowseChildrenRequest BuildBrowseChildrenRequest(BrowseChildrenOptions options)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(options);
|
||||||
|
|
||||||
|
BrowseChildrenRequest request = new()
|
||||||
|
{
|
||||||
|
PageSize = BrowseChildrenPageSize,
|
||||||
|
AlarmBearingOnly = options.AlarmBearingOnly,
|
||||||
|
HistorizedOnly = options.HistorizedOnly,
|
||||||
|
};
|
||||||
|
request.CategoryIds.Add(options.CategoryIds);
|
||||||
|
request.TemplateChainContains.Add(options.TemplateChainContains);
|
||||||
|
if (!string.IsNullOrWhiteSpace(options.TagNameGlob))
|
||||||
|
{
|
||||||
|
request.TagNameGlob = options.TagNameGlob;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.IncludeAttributes.HasValue)
|
||||||
|
{
|
||||||
|
request.IncludeAttributes = options.IncludeAttributes.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Subscribes to Galaxy deploy events. The server emits a bootstrap event with the
|
||||||
|
/// current state on subscribe so callers can prime their cache, then emits one event
|
||||||
|
/// per new <c>time_of_last_deploy</c>. Pass <paramref name="lastSeenDeployTime"/> to
|
||||||
|
/// suppress the bootstrap when the caller already holds the current deploy time.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Streaming RPCs are not wrapped by the unary safe-read retry pipeline. If the
|
||||||
|
/// stream is interrupted the caller must reopen it; the server does not guarantee
|
||||||
|
/// at-least-once delivery beyond the per-subscriber buffer (gaps in
|
||||||
|
/// <see cref="DeployEvent.Sequence"/> indicate dropped events).
|
||||||
|
/// </remarks>
|
||||||
|
/// <param name="lastSeenDeployTime">Optional timestamp to suppress the bootstrap event.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>An async enumerable of deploy events.</returns>
|
||||||
|
public IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
|
||||||
|
DateTimeOffset? lastSeenDeployTime = null,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
WatchDeployEventsRequest request = new();
|
||||||
|
if (lastSeenDeployTime is { } seen)
|
||||||
|
{
|
||||||
|
request.LastSeenDeployTime = Timestamp.FromDateTimeOffset(seen);
|
||||||
|
}
|
||||||
|
|
||||||
|
return WatchDeployEventsRawAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Subscribes to Galaxy deploy events without result wrapping.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The watch-deploy-events request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>An async enumerable of raw deploy events.</returns>
|
||||||
|
public IAsyncEnumerable<DeployEvent> WatchDeployEventsRawAsync(
|
||||||
|
WatchDeployEventsRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return WatchDeployEventsCoreAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async IAsyncEnumerable<DeployEvent> WatchDeployEventsCoreAsync(
|
||||||
|
WatchDeployEventsRequest request,
|
||||||
|
[EnumeratorCancellation] CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await foreach (DeployEvent deployEvent in _transport
|
||||||
|
.WatchDeployEventsAsync(request, CreateStreamCallOptions(cancellationToken))
|
||||||
|
.WithCancellation(cancellationToken)
|
||||||
|
.ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
yield return deployEvent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Closes the gRPC channel and releases resources.
|
||||||
|
/// </summary>
|
||||||
|
public ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
if (_disposed)
|
||||||
|
{
|
||||||
|
return ValueTask.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
_disposed = true;
|
||||||
|
_channel?.Dispose();
|
||||||
|
return ValueTask.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates gRPC call options with the client's default timeout and API-key authorization.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The call options.</returns>
|
||||||
|
internal CallOptions CreateCallOptions(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return CreateCallOptions(cancellationToken, Options.DefaultCallTimeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates gRPC call options for streaming RPCs with the stream timeout and API-key authorization.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The stream call options.</returns>
|
||||||
|
internal CallOptions CreateStreamCallOptions(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return CreateCallOptions(cancellationToken, Options.StreamTimeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates gRPC call options with the specified timeout and API-key authorization.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <param name="timeout">Optional timeout duration.</param>
|
||||||
|
/// <returns>The call options.</returns>
|
||||||
|
internal CallOptions CreateCallOptions(
|
||||||
|
CancellationToken cancellationToken,
|
||||||
|
TimeSpan? timeout)
|
||||||
|
{
|
||||||
|
Metadata headers = new()
|
||||||
|
{
|
||||||
|
{ "authorization", $"Bearer {Options.ApiKey}" },
|
||||||
|
};
|
||||||
|
|
||||||
|
return new CallOptions(
|
||||||
|
headers,
|
||||||
|
timeout is null ? null : DateTime.UtcNow.Add(timeout.Value),
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<T> ExecuteSafeUnaryAsync<T>(
|
||||||
|
Func<CancellationToken, Task<T>> call,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||||
|
timeout.CancelAfter(Options.DefaultCallTimeout);
|
||||||
|
|
||||||
|
return await _safeUnaryRetryPipeline.ExecuteAsync(
|
||||||
|
async token => await call(token).ConfigureAwait(false),
|
||||||
|
timeout.Token)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HttpMessageHandler CreateHttpHandler(MxGatewayClientOptions options)
|
||||||
|
{
|
||||||
|
SocketsHttpHandler handler = new()
|
||||||
|
{
|
||||||
|
ConnectTimeout = options.ConnectTimeout,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (options.UseTls)
|
||||||
|
{
|
||||||
|
handler.SslOptions = new SslClientAuthenticationOptions();
|
||||||
|
if (!string.IsNullOrWhiteSpace(options.ServerNameOverride))
|
||||||
|
{
|
||||||
|
handler.SslOptions.TargetHost = options.ServerNameOverride;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(options.CaCertificatePath))
|
||||||
|
{
|
||||||
|
X509Certificate2 trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath);
|
||||||
|
handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, chain, errors) =>
|
||||||
|
{
|
||||||
|
if (certificate is null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
using X509Chain customChain = new();
|
||||||
|
customChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
||||||
|
customChain.ChainPolicy.CustomTrustStore.Add(trustedRoot);
|
||||||
|
customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||||
|
customChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
|
||||||
|
X509Certificate2 certificateToValidate = certificate as X509Certificate2
|
||||||
|
?? X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert));
|
||||||
|
return customChain.Build(certificateToValidate);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ThrowIfDisposed()
|
||||||
|
{
|
||||||
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// gRPC implementation of IGalaxyRepositoryClientTransport.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class GrpcGalaxyRepositoryClientTransport(
|
||||||
|
MxGatewayClientOptions options,
|
||||||
|
GalaxyRepository.GalaxyRepositoryClient rawClient) : IGalaxyRepositoryClientTransport
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the gateway client options.
|
||||||
|
/// </summary>
|
||||||
|
public MxGatewayClientOptions Options { get; } = options;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the underlying gRPC client.
|
||||||
|
/// </summary>
|
||||||
|
public GalaxyRepository.GalaxyRepositoryClient RawClient { get; } = rawClient;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
GalaxyRepository.GalaxyRepositoryClient? IGalaxyRepositoryClientTransport.RawClient => RawClient;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<TestConnectionReply> TestConnectionAsync(
|
||||||
|
TestConnectionRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await RawClient.TestConnectionAsync(request, callOptions)
|
||||||
|
.ResponseAsync
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, callOptions.CancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<GetLastDeployTimeReply> GetLastDeployTimeAsync(
|
||||||
|
GetLastDeployTimeRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await RawClient.GetLastDeployTimeAsync(request, callOptions)
|
||||||
|
.ResponseAsync
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, callOptions.CancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<DiscoverHierarchyReply> DiscoverHierarchyAsync(
|
||||||
|
DiscoverHierarchyRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await RawClient.DiscoverHierarchyAsync(request, callOptions)
|
||||||
|
.ResponseAsync
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, callOptions.CancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<BrowseChildrenReply> BrowseChildrenAsync(
|
||||||
|
BrowseChildrenRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await RawClient.BrowseChildrenAsync(request, callOptions)
|
||||||
|
.ResponseAsync
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, callOptions.CancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
|
||||||
|
WatchDeployEventsRequest request,
|
||||||
|
CallOptions callOptions,
|
||||||
|
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
CancellationToken effectiveCancellationToken = cancellationToken.CanBeCanceled
|
||||||
|
? cancellationToken
|
||||||
|
: callOptions.CancellationToken;
|
||||||
|
|
||||||
|
using AsyncServerStreamingCall<DeployEvent> call = RawClient.WatchDeployEvents(request, callOptions);
|
||||||
|
|
||||||
|
IAsyncStreamReader<DeployEvent> responseStream = call.ResponseStream;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
DeployEvent? deployEvent;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!await responseStream.MoveNext(effectiveCancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
deployEvent = responseStream.Current;
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, effectiveCancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return deployEvent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
IAsyncEnumerable<DeployEvent> IGalaxyRepositoryClientTransport.WatchDeployEventsAsync(
|
||||||
|
WatchDeployEventsRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
return WatchDeployEventsAsync(request, callOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Exception MapRpcException(
|
||||||
|
RpcException exception,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (cancellationToken.IsCancellationRequested || exception.StatusCode == StatusCode.Cancelled)
|
||||||
|
{
|
||||||
|
return new OperationCanceledException(
|
||||||
|
exception.Status.Detail,
|
||||||
|
exception,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
return exception.StatusCode switch
|
||||||
|
{
|
||||||
|
StatusCode.Unauthenticated => new MxGatewayAuthenticationException(
|
||||||
|
exception.Status.Detail,
|
||||||
|
innerException: exception),
|
||||||
|
StatusCode.PermissionDenied => new MxGatewayAuthorizationException(
|
||||||
|
exception.Status.Detail,
|
||||||
|
innerException: exception),
|
||||||
|
_ => new MxGatewayException(exception.Status.Detail, exception),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// gRPC implementation of IMxGatewayClientTransport.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class GrpcMxGatewayClientTransport(
|
||||||
|
MxGatewayClientOptions options,
|
||||||
|
MxAccessGateway.MxAccessGatewayClient rawClient) : IMxGatewayClientTransport
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the gateway client options.
|
||||||
|
/// </summary>
|
||||||
|
public MxGatewayClientOptions Options { get; } = options;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the underlying gRPC client.
|
||||||
|
/// </summary>
|
||||||
|
public MxAccessGateway.MxAccessGatewayClient RawClient { get; } = rawClient;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
MxAccessGateway.MxAccessGatewayClient? IMxGatewayClientTransport.RawClient => RawClient;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<OpenSessionReply> OpenSessionAsync(
|
||||||
|
OpenSessionRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await RawClient.OpenSessionAsync(request, callOptions)
|
||||||
|
.ResponseAsync
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, callOptions.CancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<CloseSessionReply> CloseSessionAsync(
|
||||||
|
CloseSessionRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await RawClient.CloseSessionAsync(request, callOptions)
|
||||||
|
.ResponseAsync
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, callOptions.CancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<MxCommandReply> InvokeAsync(
|
||||||
|
MxCommandRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await RawClient.InvokeAsync(request, callOptions)
|
||||||
|
.ResponseAsync
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, callOptions.CancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
||||||
|
StreamEventsRequest request,
|
||||||
|
CallOptions callOptions,
|
||||||
|
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
CancellationToken effectiveCancellationToken = cancellationToken.CanBeCanceled
|
||||||
|
? cancellationToken
|
||||||
|
: callOptions.CancellationToken;
|
||||||
|
|
||||||
|
using AsyncServerStreamingCall<MxEvent> call = RawClient.StreamEvents(request, callOptions);
|
||||||
|
|
||||||
|
IAsyncStreamReader<MxEvent> responseStream = call.ResponseStream;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
MxEvent? gatewayEvent;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!await responseStream.MoveNext(effectiveCancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
gatewayEvent = responseStream.Current;
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, effectiveCancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return gatewayEvent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
IAsyncEnumerable<MxEvent> IMxGatewayClientTransport.StreamEventsAsync(
|
||||||
|
StreamEventsRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
return StreamEventsAsync(request, callOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<AcknowledgeAlarmReply> AcknowledgeAlarmAsync(
|
||||||
|
AcknowledgeAlarmRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await RawClient.AcknowledgeAlarmAsync(request, callOptions)
|
||||||
|
.ResponseAsync
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, callOptions.CancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async IAsyncEnumerable<ActiveAlarmSnapshot> QueryActiveAlarmsAsync(
|
||||||
|
QueryActiveAlarmsRequest request,
|
||||||
|
CallOptions callOptions,
|
||||||
|
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
CancellationToken effectiveCancellationToken = cancellationToken.CanBeCanceled
|
||||||
|
? cancellationToken
|
||||||
|
: callOptions.CancellationToken;
|
||||||
|
|
||||||
|
using AsyncServerStreamingCall<ActiveAlarmSnapshot> call = RawClient.QueryActiveAlarms(request, callOptions);
|
||||||
|
|
||||||
|
IAsyncStreamReader<ActiveAlarmSnapshot> responseStream = call.ResponseStream;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
ActiveAlarmSnapshot? snapshot;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!await responseStream.MoveNext(effectiveCancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
snapshot = responseStream.Current;
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, effectiveCancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return snapshot;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
IAsyncEnumerable<ActiveAlarmSnapshot> IMxGatewayClientTransport.QueryActiveAlarmsAsync(
|
||||||
|
QueryActiveAlarmsRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
return QueryActiveAlarmsAsync(request, callOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async IAsyncEnumerable<AlarmFeedMessage> StreamAlarmsAsync(
|
||||||
|
StreamAlarmsRequest request,
|
||||||
|
CallOptions callOptions,
|
||||||
|
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
CancellationToken effectiveCancellationToken = cancellationToken.CanBeCanceled
|
||||||
|
? cancellationToken
|
||||||
|
: callOptions.CancellationToken;
|
||||||
|
|
||||||
|
using AsyncServerStreamingCall<AlarmFeedMessage> call = RawClient.StreamAlarms(request, callOptions);
|
||||||
|
|
||||||
|
IAsyncStreamReader<AlarmFeedMessage> responseStream = call.ResponseStream;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
AlarmFeedMessage? message;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!await responseStream.MoveNext(effectiveCancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
message = responseStream.Current;
|
||||||
|
}
|
||||||
|
catch (RpcException exception)
|
||||||
|
{
|
||||||
|
throw MapRpcException(exception, effectiveCancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
IAsyncEnumerable<AlarmFeedMessage> IMxGatewayClientTransport.StreamAlarmsAsync(
|
||||||
|
StreamAlarmsRequest request,
|
||||||
|
CallOptions callOptions)
|
||||||
|
{
|
||||||
|
return StreamAlarmsAsync(request, callOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Exception MapRpcException(
|
||||||
|
RpcException exception,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (cancellationToken.IsCancellationRequested || exception.StatusCode == StatusCode.Cancelled)
|
||||||
|
{
|
||||||
|
return new OperationCanceledException(
|
||||||
|
exception.Status.Detail,
|
||||||
|
exception,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
return exception.StatusCode switch
|
||||||
|
{
|
||||||
|
StatusCode.Unauthenticated => new MxGatewayAuthenticationException(
|
||||||
|
exception.Status.Detail,
|
||||||
|
innerException: exception),
|
||||||
|
StatusCode.PermissionDenied => new MxGatewayAuthorizationException(
|
||||||
|
exception.Status.Detail,
|
||||||
|
innerException: exception),
|
||||||
|
_ => new MxGatewayException(exception.Status.Detail, exception),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Transport layer for Galaxy Repository gRPC operations.</summary>
|
||||||
|
internal interface IGalaxyRepositoryClientTransport
|
||||||
|
{
|
||||||
|
/// <summary>Gets the client options used to configure this transport.</summary>
|
||||||
|
MxGatewayClientOptions Options { get; }
|
||||||
|
|
||||||
|
/// <summary>Gets the underlying gRPC client, or <c>null</c> if not yet initialized.</summary>
|
||||||
|
GalaxyRepository.GalaxyRepositoryClient? RawClient { get; }
|
||||||
|
|
||||||
|
/// <summary>Tests the connection to the Galaxy Repository server.</summary>
|
||||||
|
/// <param name="request">The test connection request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
||||||
|
Task<TestConnectionReply> TestConnectionAsync(
|
||||||
|
TestConnectionRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
|
||||||
|
/// <summary>Gets the last deploy time from the Galaxy Repository server.</summary>
|
||||||
|
/// <param name="request">The get last deploy time request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
||||||
|
Task<GetLastDeployTimeReply> GetLastDeployTimeAsync(
|
||||||
|
GetLastDeployTimeRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
|
||||||
|
/// <summary>Discovers the object hierarchy in the Galaxy Repository.</summary>
|
||||||
|
/// <param name="request">The discover hierarchy request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
||||||
|
Task<DiscoverHierarchyReply> DiscoverHierarchyAsync(
|
||||||
|
DiscoverHierarchyRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
|
||||||
|
/// <summary>Returns direct children of a parent in the Galaxy hierarchy.</summary>
|
||||||
|
/// <param name="request">The browse children request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
||||||
|
Task<BrowseChildrenReply> BrowseChildrenAsync(
|
||||||
|
BrowseChildrenRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
|
||||||
|
/// <summary>Watches for deployment events from the Galaxy Repository server.</summary>
|
||||||
|
/// <param name="request">The watch deploy events request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options (timeout, cancellation, etc.).</param>
|
||||||
|
IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
|
||||||
|
WatchDeployEventsRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
internal interface IMxGatewayClientTransport
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the client configuration options.
|
||||||
|
/// </summary>
|
||||||
|
MxGatewayClientOptions Options { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the underlying gRPC client, if available.
|
||||||
|
/// </summary>
|
||||||
|
MxAccessGateway.MxAccessGatewayClient? RawClient { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Opens a new gateway session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Session open request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options.</param>
|
||||||
|
/// <returns>The session open reply.</returns>
|
||||||
|
Task<OpenSessionReply> OpenSessionAsync(
|
||||||
|
OpenSessionRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Closes an open gateway session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Session close request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options.</param>
|
||||||
|
/// <returns>The session close reply.</returns>
|
||||||
|
Task<CloseSessionReply> CloseSessionAsync(
|
||||||
|
CloseSessionRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Invokes an MXAccess command on the session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The command request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options.</param>
|
||||||
|
/// <returns>The command reply.</returns>
|
||||||
|
Task<MxCommandReply> InvokeAsync(
|
||||||
|
MxCommandRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Streams events from the session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The stream events request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options.</param>
|
||||||
|
/// <returns>An async enumerable of events.</returns>
|
||||||
|
IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
||||||
|
StreamEventsRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Acknowledges an active MXAccess alarm condition.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The acknowledge request.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options.</param>
|
||||||
|
/// <returns>The acknowledge reply with native MxStatus.</returns>
|
||||||
|
Task<AcknowledgeAlarmReply> AcknowledgeAlarmAsync(
|
||||||
|
AcknowledgeAlarmRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Streams a snapshot of all alarms currently in Active or ActiveAcked state — the
|
||||||
|
/// ConditionRefresh equivalent for the gateway.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The query request, optionally scoped by alarm-reference prefix.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options.</param>
|
||||||
|
/// <returns>An async enumerable of active-alarm snapshots.</returns>
|
||||||
|
IAsyncEnumerable<ActiveAlarmSnapshot> QueryActiveAlarmsAsync(
|
||||||
|
QueryActiveAlarmsRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attaches to the gateway's central alarm feed — the current active-alarm
|
||||||
|
/// snapshot followed by live transitions.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The stream request, optionally scoped by alarm-reference prefix.</param>
|
||||||
|
/// <param name="callOptions">gRPC call options.</param>
|
||||||
|
/// <returns>An async enumerable of alarm feed messages.</returns>
|
||||||
|
IAsyncEnumerable<AlarmFeedMessage> StreamAlarmsAsync(
|
||||||
|
StreamAlarmsRequest request,
|
||||||
|
CallOptions callOptions);
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One node in a lazy-loaded Galaxy browse tree. Holds the underlying
|
||||||
|
/// <see cref="GalaxyObject"/> and exposes <see cref="ExpandAsync"/> to fetch
|
||||||
|
/// its direct children on demand. Expansion is one-shot: a second call is a
|
||||||
|
/// no-op. Pagination of large sibling sets is handled internally.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class LazyBrowseNode
|
||||||
|
{
|
||||||
|
private readonly GalaxyRepositoryClient _client;
|
||||||
|
private readonly BrowseChildrenOptions _options;
|
||||||
|
private readonly List<LazyBrowseNode> _children = [];
|
||||||
|
private readonly SemaphoreSlim _expandLock = new(1, 1);
|
||||||
|
private bool _isExpanded;
|
||||||
|
|
||||||
|
internal LazyBrowseNode(
|
||||||
|
GalaxyRepositoryClient client,
|
||||||
|
GalaxyObject @object,
|
||||||
|
bool hasChildrenHint,
|
||||||
|
BrowseChildrenOptions options)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
Object = @object;
|
||||||
|
HasChildrenHint = hasChildrenHint;
|
||||||
|
_options = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The underlying Galaxy object for this node.</summary>
|
||||||
|
public GalaxyObject Object { get; }
|
||||||
|
|
||||||
|
/// <summary>True when the server reports this node has at least one matching descendant.</summary>
|
||||||
|
public bool HasChildrenHint { get; }
|
||||||
|
|
||||||
|
/// <summary>Direct children loaded by <see cref="ExpandAsync"/>; empty until then.</summary>
|
||||||
|
public IReadOnlyList<LazyBrowseNode> Children => _children;
|
||||||
|
|
||||||
|
/// <summary>True after the first <see cref="ExpandAsync"/> call completes.</summary>
|
||||||
|
public bool IsExpanded => _isExpanded;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fetches direct children from the gateway and populates <see cref="Children"/>.
|
||||||
|
/// Idempotent: subsequent calls are no-ops.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Thread-safe: concurrent callers see exactly one fetch; subsequent callers
|
||||||
|
/// (after the first completes) return immediately.
|
||||||
|
/// </remarks>
|
||||||
|
/// <param name="cancellationToken">Token to observe for cancellation.</param>
|
||||||
|
public async Task ExpandAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (_isExpanded)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _expandLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_isExpanded)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string pageToken = string.Empty;
|
||||||
|
HashSet<string> seenPageTokens = new(StringComparer.Ordinal);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
BrowseChildrenRequest request = GalaxyRepositoryClient.BuildBrowseChildrenRequest(_options);
|
||||||
|
request.ParentGobjectId = Object.GobjectId;
|
||||||
|
request.PageToken = pageToken;
|
||||||
|
|
||||||
|
BrowseChildrenReply reply = await _client
|
||||||
|
.BrowseChildrenRawAsync(request, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
for (int i = 0; i < reply.Children.Count; i++)
|
||||||
|
{
|
||||||
|
bool hint = i < reply.ChildHasChildren.Count && reply.ChildHasChildren[i];
|
||||||
|
_children.Add(new LazyBrowseNode(_client, reply.Children[i], hint, _options));
|
||||||
|
}
|
||||||
|
|
||||||
|
pageToken = reply.NextPageToken;
|
||||||
|
if (!string.IsNullOrWhiteSpace(pageToken) && !seenPageTokens.Add(pageToken))
|
||||||
|
{
|
||||||
|
throw new MxGatewayException(
|
||||||
|
$"Galaxy BrowseChildren returned a repeated page token '{pageToken}'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (!string.IsNullOrWhiteSpace(pageToken));
|
||||||
|
|
||||||
|
_isExpanded = true;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_expandLock.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Exception thrown when an MXAccess command fails with a non-zero HResult or failing status.</summary>
|
||||||
|
public sealed class MxAccessException : MxGatewayCommandException
|
||||||
|
{
|
||||||
|
/// <summary>Initializes a new instance with the given message, reply, and optional inner exception.</summary>
|
||||||
|
/// <param name="message">The error message describing the MXAccess failure.</param>
|
||||||
|
/// <param name="reply">The MxCommandReply containing the failure details (statuses, HResult, etc.).</param>
|
||||||
|
/// <param name="innerException">The underlying exception, if any.</param>
|
||||||
|
public MxAccessException(
|
||||||
|
string message,
|
||||||
|
MxCommandReply reply,
|
||||||
|
Exception? innerException = null)
|
||||||
|
: base(
|
||||||
|
message,
|
||||||
|
reply.SessionId,
|
||||||
|
reply.CorrelationId,
|
||||||
|
reply.ProtocolStatus,
|
||||||
|
reply.HasHresult ? reply.Hresult : null,
|
||||||
|
reply.Statuses.ToArray(),
|
||||||
|
innerException)
|
||||||
|
{
|
||||||
|
Reply = reply;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Gets the underlying MxCommandReply containing full failure details.</summary>
|
||||||
|
public MxCommandReply Reply { get; }
|
||||||
|
}
|
||||||
+7
-2
@@ -1,9 +1,12 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Extension methods for checking MxCommandReply success conditions.</summary>
|
||||||
public static class MxCommandReplyExtensions
|
public static class MxCommandReplyExtensions
|
||||||
{
|
{
|
||||||
|
/// <summary>Validates that the reply has a successful protocol status (Ok or MxAccessFailure), throwing a gateway exception if not.</summary>
|
||||||
|
/// <param name="reply">The command reply to check.</param>
|
||||||
public static MxCommandReply EnsureProtocolSuccess(this MxCommandReply reply)
|
public static MxCommandReply EnsureProtocolSuccess(this MxCommandReply reply)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(reply);
|
ArgumentNullException.ThrowIfNull(reply);
|
||||||
@@ -19,6 +22,8 @@ public static class MxCommandReplyExtensions
|
|||||||
throw CreateProtocolException(reply, code);
|
throw CreateProtocolException(reply, code);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Validates that the reply indicates MXAccess success (no HResult or status failures), throwing MxAccessException if not.</summary>
|
||||||
|
/// <param name="reply">The command reply to check.</param>
|
||||||
public static MxCommandReply EnsureMxAccessSuccess(this MxCommandReply reply)
|
public static MxCommandReply EnsureMxAccessSuccess(this MxCommandReply reply)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(reply);
|
ArgumentNullException.ThrowIfNull(reply);
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Exception thrown when an API key is invalid, expired, or malformed.</summary>
|
||||||
|
public sealed class MxGatewayAuthenticationException : MxGatewayException
|
||||||
|
{
|
||||||
|
/// <summary>Initializes a new instance with the given details.</summary>
|
||||||
|
/// <param name="message">The error message describing the authentication failure.</param>
|
||||||
|
/// <param name="sessionId">The session ID, if available.</param>
|
||||||
|
/// <param name="correlationId">The correlation ID for tracing, if available.</param>
|
||||||
|
/// <param name="protocolStatus">The protocol status details, if available.</param>
|
||||||
|
/// <param name="hResult">The HResult code, if available.</param>
|
||||||
|
/// <param name="statuses">The MXAccess statuses, if available.</param>
|
||||||
|
/// <param name="innerException">The underlying exception, if any.</param>
|
||||||
|
public MxGatewayAuthenticationException(
|
||||||
|
string message,
|
||||||
|
string? sessionId = null,
|
||||||
|
string? correlationId = null,
|
||||||
|
ProtocolStatus? protocolStatus = null,
|
||||||
|
int? hResult = null,
|
||||||
|
IReadOnlyList<MxStatusProxy>? statuses = null,
|
||||||
|
Exception? innerException = null)
|
||||||
|
: base(
|
||||||
|
message,
|
||||||
|
sessionId,
|
||||||
|
correlationId,
|
||||||
|
protocolStatus,
|
||||||
|
hResult,
|
||||||
|
statuses ?? [],
|
||||||
|
innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Exception thrown when the API key lacks required scopes for an operation.</summary>
|
||||||
|
public sealed class MxGatewayAuthorizationException : MxGatewayException
|
||||||
|
{
|
||||||
|
/// <summary>Initializes a new instance with the given details.</summary>
|
||||||
|
/// <param name="message">The error message describing the authorization failure.</param>
|
||||||
|
/// <param name="sessionId">The session ID, if available.</param>
|
||||||
|
/// <param name="correlationId">The correlation ID for tracing, if available.</param>
|
||||||
|
/// <param name="protocolStatus">The protocol status details, if available.</param>
|
||||||
|
/// <param name="hResult">The HResult code, if available.</param>
|
||||||
|
/// <param name="statuses">The MXAccess statuses, if available.</param>
|
||||||
|
/// <param name="innerException">The underlying exception, if any.</param>
|
||||||
|
public MxGatewayAuthorizationException(
|
||||||
|
string message,
|
||||||
|
string? sessionId = null,
|
||||||
|
string? correlationId = null,
|
||||||
|
ProtocolStatus? protocolStatus = null,
|
||||||
|
int? hResult = null,
|
||||||
|
IReadOnlyList<MxStatusProxy>? statuses = null,
|
||||||
|
Exception? innerException = null)
|
||||||
|
: base(
|
||||||
|
message,
|
||||||
|
sessionId,
|
||||||
|
correlationId,
|
||||||
|
protocolStatus,
|
||||||
|
hResult,
|
||||||
|
statuses ?? [],
|
||||||
|
innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using Grpc.Net.Client;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
using Polly;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Security;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Provides the .NET client entry point for the public MXAccess Gateway gRPC API.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class MxGatewayClient : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private readonly GrpcChannel _channel;
|
||||||
|
private readonly IMxGatewayClientTransport _transport;
|
||||||
|
private readonly ResiliencePipeline _safeUnaryRetryPipeline;
|
||||||
|
private bool _disposed;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="MxGatewayClient"/> with given options and transport.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="options">Client configuration options.</param>
|
||||||
|
/// <param name="transport">Transport implementation for gateway communication.</param>
|
||||||
|
internal MxGatewayClient(
|
||||||
|
MxGatewayClientOptions options,
|
||||||
|
IMxGatewayClientTransport transport)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(options);
|
||||||
|
options.Validate();
|
||||||
|
|
||||||
|
Options = options;
|
||||||
|
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
||||||
|
_safeUnaryRetryPipeline = MxGatewayClientRetryPolicy.Create(
|
||||||
|
options.Retry,
|
||||||
|
options.LoggerFactory?.CreateLogger<MxGatewayClient>());
|
||||||
|
_channel = null!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private MxGatewayClient(
|
||||||
|
GrpcChannel channel,
|
||||||
|
IMxGatewayClientTransport transport)
|
||||||
|
{
|
||||||
|
_channel = channel;
|
||||||
|
_transport = transport;
|
||||||
|
Options = transport.Options;
|
||||||
|
_safeUnaryRetryPipeline = MxGatewayClientRetryPolicy.Create(
|
||||||
|
Options.Retry,
|
||||||
|
Options.LoggerFactory?.CreateLogger<MxGatewayClient>());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the client configuration options.
|
||||||
|
/// </summary>
|
||||||
|
public MxGatewayClientOptions Options { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the underlying generated gRPC client.
|
||||||
|
/// </summary>
|
||||||
|
public MxAccessGateway.MxAccessGatewayClient RawClient =>
|
||||||
|
_transport.RawClient
|
||||||
|
?? throw new InvalidOperationException("The raw generated gRPC client is not available for this client instance.");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a new gateway client with the given options.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="options">Client configuration options.</param>
|
||||||
|
/// <returns>A new gateway client instance.</returns>
|
||||||
|
public static MxGatewayClient Create(MxGatewayClientOptions options)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(options);
|
||||||
|
options.Validate();
|
||||||
|
|
||||||
|
HttpMessageHandler handler = CreateHttpHandler(options);
|
||||||
|
var channel = GrpcChannel.ForAddress(
|
||||||
|
options.Endpoint,
|
||||||
|
new GrpcChannelOptions
|
||||||
|
{
|
||||||
|
HttpHandler = handler,
|
||||||
|
LoggerFactory = options.LoggerFactory,
|
||||||
|
MaxReceiveMessageSize = options.MaxGrpcMessageBytes,
|
||||||
|
MaxSendMessageSize = options.MaxGrpcMessageBytes,
|
||||||
|
});
|
||||||
|
|
||||||
|
return new MxGatewayClient(
|
||||||
|
channel,
|
||||||
|
new GrpcMxGatewayClientTransport(
|
||||||
|
options,
|
||||||
|
new MxAccessGateway.MxAccessGatewayClient(channel)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Opens a new gateway session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Session open request; defaults to empty request if null.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>A wrapped gateway session.</returns>
|
||||||
|
public async Task<MxGatewaySession> OpenSessionAsync(
|
||||||
|
OpenSessionRequest? request = null,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
OpenSessionReply reply = await OpenSessionRawAsync(
|
||||||
|
request ?? new OpenSessionRequest(),
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
return new MxGatewaySession(this, reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Opens a new gateway session and returns the raw protobuf reply.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Session open request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The raw gateway session open reply.</returns>
|
||||||
|
public Task<OpenSessionReply> OpenSessionRawAsync(
|
||||||
|
OpenSessionRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return _transport.OpenSessionAsync(request, CreateCallOptions(cancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Closes an open gateway session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Session close request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The session close reply.</returns>
|
||||||
|
public Task<CloseSessionReply> CloseSessionRawAsync(
|
||||||
|
CloseSessionRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return ExecuteSafeUnaryAsync(
|
||||||
|
token => _transport.CloseSessionAsync(request, CreateCallOptions(token)),
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Invokes an MXAccess command on the open session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The command request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The command reply.</returns>
|
||||||
|
public Task<MxCommandReply> InvokeAsync(
|
||||||
|
MxCommandRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
if (MxGatewayClientRetryPolicy.IsRetryableCommand(request.Command?.Kind ?? MxCommandKind.Unspecified))
|
||||||
|
{
|
||||||
|
return ExecuteSafeUnaryAsync(
|
||||||
|
token => _transport.InvokeAsync(request, CreateCallOptions(token)),
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
return _transport.InvokeAsync(request, CreateCallOptions(cancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Streams events from the gateway session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The stream events request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>An async enumerable of events.</returns>
|
||||||
|
public IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
||||||
|
StreamEventsRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return _transport.StreamEventsAsync(request, CreateStreamCallOptions(cancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Acknowledges an active MXAccess alarm condition through the gateway. The
|
||||||
|
/// gateway authenticates the request against the API key's <c>invoke:alarm-ack</c>
|
||||||
|
/// scope and forwards the acknowledge to the worker's MXAccess session;
|
||||||
|
/// the resulting <see cref="MxStatusProxy"/> is returned in the reply.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The acknowledge request — alarm reference, comment, operator user.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||||
|
/// <returns>The acknowledge reply with protocol + native MxStatus.</returns>
|
||||||
|
public Task<AcknowledgeAlarmReply> AcknowledgeAlarmAsync(
|
||||||
|
AcknowledgeAlarmRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return ExecuteSafeUnaryAsync(
|
||||||
|
token => _transport.AcknowledgeAlarmAsync(request, CreateCallOptions(token)),
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Streams a snapshot of all alarms currently Active or ActiveAcked — the gateway's
|
||||||
|
/// ConditionRefresh equivalent. Used after reconnect to seed the local Part 9 state
|
||||||
|
/// machine, or to reconcile alarms that may have been missed during a transport
|
||||||
|
/// blip. Optionally scoped by alarm-reference prefix
|
||||||
|
/// (<see cref="QueryActiveAlarmsRequest.AlarmFilterPrefix"/>) so a partial refresh
|
||||||
|
/// can target an equipment sub-tree.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The query request, optionally scoped by alarm-reference prefix.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the stream.</param>
|
||||||
|
/// <returns>An async enumerable of active-alarm snapshots.</returns>
|
||||||
|
public IAsyncEnumerable<ActiveAlarmSnapshot> QueryActiveAlarmsAsync(
|
||||||
|
QueryActiveAlarmsRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return _transport.QueryActiveAlarmsAsync(request, CreateStreamCallOptions(cancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attaches to the gateway's central alarm feed. The stream opens with one
|
||||||
|
/// <see cref="AlarmFeedMessage"/> per currently-active alarm (the
|
||||||
|
/// ConditionRefresh snapshot), then a single <c>snapshot_complete</c>, then a
|
||||||
|
/// <c>transition</c> for every subsequent raise / acknowledge / clear. Served
|
||||||
|
/// by the gateway's always-on alarm monitor — no worker session is opened, so
|
||||||
|
/// any number of clients may attach. Optionally scoped by alarm-reference
|
||||||
|
/// prefix (<see cref="StreamAlarmsRequest.AlarmFilterPrefix"/>).
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The stream request, optionally scoped by alarm-reference prefix.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the stream.</param>
|
||||||
|
/// <returns>An async enumerable of alarm feed messages.</returns>
|
||||||
|
public IAsyncEnumerable<AlarmFeedMessage> StreamAlarmsAsync(
|
||||||
|
StreamAlarmsRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ThrowIfDisposed();
|
||||||
|
|
||||||
|
return _transport.StreamAlarmsAsync(request, CreateStreamCallOptions(cancellationToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Disposes the client and releases all resources.
|
||||||
|
/// </summary>
|
||||||
|
public ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
if (_disposed)
|
||||||
|
{
|
||||||
|
return ValueTask.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
_disposed = true;
|
||||||
|
_channel?.Dispose();
|
||||||
|
return ValueTask.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates gRPC call options with default timeout and authorization.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the call.</param>
|
||||||
|
/// <returns>Configured call options.</returns>
|
||||||
|
internal CallOptions CreateCallOptions(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return CreateCallOptions(cancellationToken, Options.DefaultCallTimeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates gRPC call options for streaming with stream timeout and authorization.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the call.</param>
|
||||||
|
/// <returns>Configured call options.</returns>
|
||||||
|
internal CallOptions CreateStreamCallOptions(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return CreateCallOptions(cancellationToken, Options.StreamTimeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates gRPC call options with specified timeout and authorization.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token for the call.</param>
|
||||||
|
/// <param name="timeout">Optional timeout duration; null means no timeout.</param>
|
||||||
|
/// <returns>Configured call options.</returns>
|
||||||
|
internal CallOptions CreateCallOptions(
|
||||||
|
CancellationToken cancellationToken,
|
||||||
|
TimeSpan? timeout)
|
||||||
|
{
|
||||||
|
Metadata headers = new()
|
||||||
|
{
|
||||||
|
{ "authorization", $"Bearer {Options.ApiKey}" },
|
||||||
|
};
|
||||||
|
|
||||||
|
return new CallOptions(
|
||||||
|
headers,
|
||||||
|
timeout is null ? null : DateTime.UtcNow.Add(timeout.Value),
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<T> ExecuteSafeUnaryAsync<T>(
|
||||||
|
Func<CancellationToken, Task<T>> call,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||||
|
timeout.CancelAfter(Options.DefaultCallTimeout);
|
||||||
|
|
||||||
|
return await _safeUnaryRetryPipeline.ExecuteAsync(
|
||||||
|
async token => await call(token).ConfigureAwait(false),
|
||||||
|
timeout.Token)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HttpMessageHandler CreateHttpHandler(MxGatewayClientOptions options)
|
||||||
|
{
|
||||||
|
SocketsHttpHandler handler = new()
|
||||||
|
{
|
||||||
|
ConnectTimeout = options.ConnectTimeout,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (options.UseTls)
|
||||||
|
{
|
||||||
|
handler.SslOptions = new SslClientAuthenticationOptions();
|
||||||
|
if (!string.IsNullOrWhiteSpace(options.ServerNameOverride))
|
||||||
|
{
|
||||||
|
handler.SslOptions.TargetHost = options.ServerNameOverride;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(options.CaCertificatePath))
|
||||||
|
{
|
||||||
|
X509Certificate2 trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath);
|
||||||
|
handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, chain, errors) =>
|
||||||
|
{
|
||||||
|
if (certificate is null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
using X509Chain customChain = new();
|
||||||
|
customChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
||||||
|
customChain.ChainPolicy.CustomTrustStore.Add(trustedRoot);
|
||||||
|
customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
||||||
|
customChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
|
||||||
|
X509Certificate2 certificateToValidate = certificate as X509Certificate2
|
||||||
|
?? X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert));
|
||||||
|
return customChain.Build(certificateToValidate);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ThrowIfDisposed()
|
||||||
|
{
|
||||||
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-2
@@ -1,15 +1,17 @@
|
|||||||
using MxGateway.Contracts;
|
using ZB.MOM.WW.MxGateway.Contracts;
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Exposes the protocol versions compiled into this client package.
|
/// Exposes the protocol versions compiled into this client package.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class MxGatewayClientContractInfo
|
public static class MxGatewayClientContractInfo
|
||||||
{
|
{
|
||||||
|
/// <inheritdoc cref="GatewayContractInfo.GatewayProtocolVersion"/>
|
||||||
public const uint GatewayProtocolVersion =
|
public const uint GatewayProtocolVersion =
|
||||||
GatewayContractInfo.GatewayProtocolVersion;
|
GatewayContractInfo.GatewayProtocolVersion;
|
||||||
|
|
||||||
|
/// <inheritdoc cref="GatewayContractInfo.WorkerProtocolVersion"/>
|
||||||
public const uint WorkerProtocolVersion =
|
public const uint WorkerProtocolVersion =
|
||||||
GatewayContractInfo.WorkerProtocolVersion;
|
GatewayContractInfo.WorkerProtocolVersion;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Configures the gRPC channel used by the .NET MXAccess Gateway client.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class MxGatewayClientOptions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the gateway endpoint URI (required).
|
||||||
|
/// </summary>
|
||||||
|
public required Uri Endpoint { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the API key for gateway authentication (required).
|
||||||
|
/// </summary>
|
||||||
|
public required string ApiKey { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets a value indicating whether to use TLS for the gateway connection.
|
||||||
|
/// </summary>
|
||||||
|
public bool UseTls { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the path to a CA certificate file for custom certificate validation.
|
||||||
|
/// </summary>
|
||||||
|
public string? CaCertificatePath { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the server name override for SNI during TLS handshake.
|
||||||
|
/// </summary>
|
||||||
|
public string? ServerNameOverride { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the timeout for establishing connection to the gateway.
|
||||||
|
/// </summary>
|
||||||
|
public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the default timeout for unary gRPC calls.
|
||||||
|
/// </summary>
|
||||||
|
public TimeSpan DefaultCallTimeout { get; init; } = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the optional timeout for streaming gRPC calls.
|
||||||
|
/// </summary>
|
||||||
|
public TimeSpan? StreamTimeout { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the maximum size in bytes for gRPC messages.
|
||||||
|
/// </summary>
|
||||||
|
public int MaxGrpcMessageBytes { get; init; } = 16 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the retry configuration for safe unary calls.
|
||||||
|
/// </summary>
|
||||||
|
public MxGatewayClientRetryOptions Retry { get; init; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the logger factory for diagnostic logging.
|
||||||
|
/// </summary>
|
||||||
|
public ILoggerFactory? LoggerFactory { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Validates the client options for consistency and correctness.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="ArgumentNullException">Endpoint is null.</exception>
|
||||||
|
/// <exception cref="ArgumentException">Options are invalid or inconsistent.</exception>
|
||||||
|
/// <exception cref="ArgumentOutOfRangeException">Timeout values are not greater than zero.</exception>
|
||||||
|
public void Validate()
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(Endpoint);
|
||||||
|
|
||||||
|
if (!Endpoint.IsAbsoluteUri)
|
||||||
|
{
|
||||||
|
throw new ArgumentException(
|
||||||
|
"The gateway endpoint must be an absolute URI.",
|
||||||
|
nameof(Endpoint));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(ApiKey))
|
||||||
|
{
|
||||||
|
throw new ArgumentException(
|
||||||
|
"The gateway API key must not be empty.",
|
||||||
|
nameof(ApiKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ConnectTimeout <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(
|
||||||
|
nameof(ConnectTimeout),
|
||||||
|
"The connect timeout must be greater than zero.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (DefaultCallTimeout <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(
|
||||||
|
nameof(DefaultCallTimeout),
|
||||||
|
"The default call timeout must be greater than zero.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StreamTimeout is not null && StreamTimeout <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(
|
||||||
|
nameof(StreamTimeout),
|
||||||
|
"The stream timeout must be greater than zero when configured.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (MaxGrpcMessageBytes <= 0)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(
|
||||||
|
nameof(MaxGrpcMessageBytes),
|
||||||
|
"The maximum gRPC message size must be greater than zero.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (UseTls && Endpoint.Scheme != Uri.UriSchemeHttps)
|
||||||
|
{
|
||||||
|
throw new ArgumentException(
|
||||||
|
"UseTls requires an https gateway endpoint.",
|
||||||
|
nameof(Endpoint));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!UseTls && Endpoint.Scheme == Uri.UriSchemeHttps)
|
||||||
|
{
|
||||||
|
throw new ArgumentException(
|
||||||
|
"An https gateway endpoint requires UseTls.",
|
||||||
|
nameof(Endpoint));
|
||||||
|
}
|
||||||
|
|
||||||
|
Retry.Validate();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Configuration for automatic retry behavior on transient gRPC call failures.</summary>
|
||||||
|
public sealed class MxGatewayClientRetryOptions
|
||||||
|
{
|
||||||
|
/// <summary>Gets the maximum number of attempts (initial + retries); default is 2.</summary>
|
||||||
|
public int MaxAttempts { get; init; } = 2;
|
||||||
|
|
||||||
|
/// <summary>Gets the initial delay between retry attempts; default is 200 milliseconds.</summary>
|
||||||
|
public TimeSpan Delay { get; init; } = TimeSpan.FromMilliseconds(200);
|
||||||
|
|
||||||
|
/// <summary>Gets the maximum delay between retry attempts; default is 2 seconds.</summary>
|
||||||
|
public TimeSpan MaxDelay { get; init; } = TimeSpan.FromSeconds(2);
|
||||||
|
|
||||||
|
/// <summary>Gets a value indicating whether to add randomness to retry delays; default is true.</summary>
|
||||||
|
public bool UseJitter { get; init; } = true;
|
||||||
|
|
||||||
|
/// <summary>Validates the retry options and throws if any constraint is violated.</summary>
|
||||||
|
public void Validate()
|
||||||
|
{
|
||||||
|
if (MaxAttempts <= 0)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(
|
||||||
|
nameof(MaxAttempts),
|
||||||
|
"The retry max attempts value must be greater than zero.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Delay <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(
|
||||||
|
nameof(Delay),
|
||||||
|
"The retry delay must be greater than zero.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (MaxDelay <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(
|
||||||
|
nameof(MaxDelay),
|
||||||
|
"The retry max delay must be greater than zero.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (MaxDelay < Delay)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(
|
||||||
|
nameof(MaxDelay),
|
||||||
|
"The retry max delay must be greater than or equal to the retry delay.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
using Grpc.Core;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
using Polly;
|
||||||
|
using Polly.Retry;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Factory and helpers for exponential-backoff retry policies on transient gRPC failures.</summary>
|
||||||
|
internal static class MxGatewayClientRetryPolicy
|
||||||
|
{
|
||||||
|
/// <summary>Creates a Polly ResiliencePipeline that retries transient gRPC failures with exponential backoff.</summary>
|
||||||
|
/// <param name="options">Retry configuration (max attempts, delay bounds, jitter).</param>
|
||||||
|
/// <param name="logger">Optional logger for retry diagnostics.</param>
|
||||||
|
public static ResiliencePipeline Create(
|
||||||
|
MxGatewayClientRetryOptions options,
|
||||||
|
ILogger? logger)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(options);
|
||||||
|
options.Validate();
|
||||||
|
|
||||||
|
return new ResiliencePipelineBuilder()
|
||||||
|
.AddRetry(new RetryStrategyOptions
|
||||||
|
{
|
||||||
|
MaxRetryAttempts = Math.Max(0, options.MaxAttempts - 1),
|
||||||
|
BackoffType = DelayBackoffType.Exponential,
|
||||||
|
UseJitter = options.UseJitter,
|
||||||
|
Delay = options.Delay,
|
||||||
|
MaxDelay = options.MaxDelay,
|
||||||
|
ShouldHandle = new PredicateBuilder().Handle<Exception>(IsTransientGrpcFailure),
|
||||||
|
OnRetry = args =>
|
||||||
|
{
|
||||||
|
logger?.LogDebug(
|
||||||
|
args.Outcome.Exception,
|
||||||
|
"Retrying MXAccess Gateway client call after transient gRPC failure. Attempt {Attempt}.",
|
||||||
|
args.AttemptNumber + 1);
|
||||||
|
return default;
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.Build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns whether a command kind is eligible for automatic retry on transient failures.</summary>
|
||||||
|
/// <param name="kind">The command kind to check.</param>
|
||||||
|
public static bool IsRetryableCommand(MxCommandKind kind)
|
||||||
|
{
|
||||||
|
return kind is MxCommandKind.Ping
|
||||||
|
or MxCommandKind.GetSessionState
|
||||||
|
or MxCommandKind.GetWorkerInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsTransientGrpcFailure(Exception exception)
|
||||||
|
{
|
||||||
|
return exception switch
|
||||||
|
{
|
||||||
|
RpcException rpcException => IsTransientStatus(rpcException.StatusCode),
|
||||||
|
MxGatewayException { InnerException: RpcException rpcException } => IsTransientStatus(rpcException.StatusCode),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsTransientStatus(StatusCode statusCode)
|
||||||
|
{
|
||||||
|
return statusCode is StatusCode.Unavailable
|
||||||
|
or StatusCode.DeadlineExceeded
|
||||||
|
or StatusCode.ResourceExhausted;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Exception thrown when a gateway command fails due to an unclassified protocol error.</summary>
|
||||||
|
public class MxGatewayCommandException : MxGatewayException
|
||||||
|
{
|
||||||
|
/// <summary>Initializes a new instance with the given details.</summary>
|
||||||
|
/// <param name="message">The error message describing the command failure.</param>
|
||||||
|
/// <param name="sessionId">The session ID, if available.</param>
|
||||||
|
/// <param name="correlationId">The correlation ID for tracing, if available.</param>
|
||||||
|
/// <param name="protocolStatus">The protocol status details, if available.</param>
|
||||||
|
/// <param name="hResult">The HResult code, if available.</param>
|
||||||
|
/// <param name="statuses">The MXAccess statuses, if available.</param>
|
||||||
|
/// <param name="innerException">The underlying exception, if any.</param>
|
||||||
|
public MxGatewayCommandException(
|
||||||
|
string message,
|
||||||
|
string? sessionId = null,
|
||||||
|
string? correlationId = null,
|
||||||
|
ProtocolStatus? protocolStatus = null,
|
||||||
|
int? hResult = null,
|
||||||
|
IReadOnlyList<MxStatusProxy>? statuses = null,
|
||||||
|
Exception? innerException = null)
|
||||||
|
: base(
|
||||||
|
message,
|
||||||
|
sessionId,
|
||||||
|
correlationId,
|
||||||
|
protocolStatus,
|
||||||
|
hResult,
|
||||||
|
statuses ?? [],
|
||||||
|
innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Exception thrown when a gateway RPC call fails or returns an error status.
|
||||||
|
/// </summary>
|
||||||
|
public class MxGatewayException : Exception
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the MxGatewayException class with the specified message.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="message">Diagnostic message describing the failure.</param>
|
||||||
|
public MxGatewayException(string message)
|
||||||
|
: base(message)
|
||||||
|
{
|
||||||
|
Statuses = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the MxGatewayException class with the specified message and inner exception.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="message">Diagnostic message describing the failure.</param>
|
||||||
|
/// <param name="innerException">Underlying exception that caused this failure.</param>
|
||||||
|
public MxGatewayException(string message, Exception? innerException)
|
||||||
|
: base(message, innerException)
|
||||||
|
{
|
||||||
|
Statuses = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the MxGatewayException class with full diagnostic information.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="message">Diagnostic message describing the failure.</param>
|
||||||
|
/// <param name="sessionId">Session ID associated with the exception, if available.</param>
|
||||||
|
/// <param name="correlationId">Correlation ID associated with the exception, if available.</param>
|
||||||
|
/// <param name="protocolStatus">Protocol-level status returned by the gateway, if available.</param>
|
||||||
|
/// <param name="hResult">HRESULT code returned by the worker or MXAccess, if available.</param>
|
||||||
|
/// <param name="statuses">List of MXAccess status codes returned by the operation.</param>
|
||||||
|
/// <param name="innerException">Underlying exception that caused this failure.</param>
|
||||||
|
public MxGatewayException(
|
||||||
|
string message,
|
||||||
|
string? sessionId,
|
||||||
|
string? correlationId,
|
||||||
|
ProtocolStatus? protocolStatus,
|
||||||
|
int? hResult,
|
||||||
|
IReadOnlyList<MxStatusProxy> statuses,
|
||||||
|
Exception? innerException = null)
|
||||||
|
: base(message, innerException)
|
||||||
|
{
|
||||||
|
SessionId = sessionId;
|
||||||
|
CorrelationId = correlationId;
|
||||||
|
ProtocolStatus = protocolStatus;
|
||||||
|
HResultCode = hResult;
|
||||||
|
Statuses = statuses;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the session ID associated with the exception, if available.
|
||||||
|
/// </summary>
|
||||||
|
public string? SessionId { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the correlation ID associated with the exception, if available.
|
||||||
|
/// </summary>
|
||||||
|
public string? CorrelationId { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the protocol-level status returned by the gateway, if available.
|
||||||
|
/// </summary>
|
||||||
|
public ProtocolStatus? ProtocolStatus { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the HRESULT code returned by the worker or MXAccess, if available.
|
||||||
|
/// </summary>
|
||||||
|
public int? HResultCode { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the list of MXAccess status codes returned by the operation.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<MxStatusProxy> Statuses { get; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,844 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents one gateway-backed MXAccess session.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class MxGatewaySession : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private readonly MxGatewayClient _client;
|
||||||
|
private readonly SemaphoreSlim _closeLock = new(1, 1);
|
||||||
|
private CloseSessionReply? _closeReply;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new session backed by the given MXAccess gateway client.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="client">The gateway client used for commands and events.</param>
|
||||||
|
/// <param name="openSessionReply">The server's session creation response.</param>
|
||||||
|
internal MxGatewaySession(
|
||||||
|
MxGatewayClient client,
|
||||||
|
OpenSessionReply openSessionReply)
|
||||||
|
{
|
||||||
|
_client = client ?? throw new ArgumentNullException(nameof(client));
|
||||||
|
OpenSessionReply = openSessionReply ?? throw new ArgumentNullException(nameof(openSessionReply));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The session ID assigned by the gateway.
|
||||||
|
/// </summary>
|
||||||
|
public string SessionId => OpenSessionReply.SessionId;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The server's session creation response containing metadata.
|
||||||
|
/// </summary>
|
||||||
|
public OpenSessionReply OpenSessionReply { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Closes the session on the gateway. Idempotent.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The server's close-session reply.</returns>
|
||||||
|
public async Task<CloseSessionReply> CloseAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (_closeReply is not null)
|
||||||
|
{
|
||||||
|
return _closeReply;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _closeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_closeReply is not null)
|
||||||
|
{
|
||||||
|
return _closeReply;
|
||||||
|
}
|
||||||
|
|
||||||
|
_closeReply = await _client.CloseSessionRawAsync(
|
||||||
|
new CloseSessionRequest { SessionId = SessionId },
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
return _closeReply;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_closeLock.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Registers a client with the MXAccess session, returning a ServerHandle.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="clientName">Name to register.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The server handle assigned to the registered client.</returns>
|
||||||
|
public async Task<int> RegisterAsync(
|
||||||
|
string clientName,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
MxCommandReply reply = await RegisterRawAsync(clientName, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.Register?.ServerHandle ?? reply.ReturnValue.Int32Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Registers a client with the MXAccess session without error checking.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="clientName">Name to register.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<MxCommandReply> RegisterRawAsync(
|
||||||
|
string clientName,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(clientName);
|
||||||
|
|
||||||
|
return InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.Register,
|
||||||
|
Register = new RegisterCommand { ClientName = clientName },
|
||||||
|
},
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds an item to the MXAccess session, returning an ItemHandle.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemDefinition">The item tag address.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The item handle assigned to the new item.</returns>
|
||||||
|
public async Task<int> AddItemAsync(
|
||||||
|
int serverHandle,
|
||||||
|
string itemDefinition,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
MxCommandReply reply = await AddItemRawAsync(
|
||||||
|
serverHandle,
|
||||||
|
itemDefinition,
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.AddItem?.ItemHandle ?? reply.ReturnValue.Int32Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds an item to the MXAccess session without error checking.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemDefinition">The item tag address.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<MxCommandReply> AddItemRawAsync(
|
||||||
|
int serverHandle,
|
||||||
|
string itemDefinition,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(itemDefinition);
|
||||||
|
|
||||||
|
return InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.AddItem,
|
||||||
|
AddItem = new AddItemCommand
|
||||||
|
{
|
||||||
|
ServerHandle = serverHandle,
|
||||||
|
ItemDefinition = itemDefinition,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds an item with context to the MXAccess session, returning an ItemHandle.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemDefinition">The item tag address.</param>
|
||||||
|
/// <param name="itemContext">Additional context for the item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The item handle assigned to the new item.</returns>
|
||||||
|
public async Task<int> AddItem2Async(
|
||||||
|
int serverHandle,
|
||||||
|
string itemDefinition,
|
||||||
|
string itemContext,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
MxCommandReply reply = await AddItem2RawAsync(
|
||||||
|
serverHandle,
|
||||||
|
itemDefinition,
|
||||||
|
itemContext,
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.AddItem2?.ItemHandle ?? reply.ReturnValue.Int32Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds an item with context to the MXAccess session without error checking.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemDefinition">The item tag address.</param>
|
||||||
|
/// <param name="itemContext">Additional context for the item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<MxCommandReply> AddItem2RawAsync(
|
||||||
|
int serverHandle,
|
||||||
|
string itemDefinition,
|
||||||
|
string itemContext,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(itemDefinition);
|
||||||
|
|
||||||
|
return InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.AddItem2,
|
||||||
|
AddItem2 = new AddItem2Command
|
||||||
|
{
|
||||||
|
ServerHandle = serverHandle,
|
||||||
|
ItemDefinition = itemDefinition,
|
||||||
|
ItemContext = itemContext ?? string.Empty,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Subscribes to events for an item (advises in MXAccess terminology).
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
public async Task AdviseAsync(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
MxCommandReply reply = await AdviseRawAsync(serverHandle, itemHandle, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Subscribes to events for an item without error checking.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<MxCommandReply> AdviseRawAsync(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
return InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.Advise,
|
||||||
|
Advise = new AdviseCommand
|
||||||
|
{
|
||||||
|
ServerHandle = serverHandle,
|
||||||
|
ItemHandle = itemHandle,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Unsubscribes from events for an item (unadvises in MXAccess terminology).
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
public async Task UnAdviseAsync(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
MxCommandReply reply = await UnAdviseRawAsync(serverHandle, itemHandle, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Unsubscribes from events for an item without error checking.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<MxCommandReply> UnAdviseRawAsync(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
return InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.UnAdvise,
|
||||||
|
UnAdvise = new UnAdviseCommand
|
||||||
|
{
|
||||||
|
ServerHandle = serverHandle,
|
||||||
|
ItemHandle = itemHandle,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Removes an item from the MXAccess session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
public async Task RemoveItemAsync(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
MxCommandReply reply = await RemoveItemRawAsync(serverHandle, itemHandle, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Removes an item from the MXAccess session without error checking.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<MxCommandReply> RemoveItemRawAsync(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
return InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.RemoveItem,
|
||||||
|
RemoveItem = new RemoveItemCommand
|
||||||
|
{
|
||||||
|
ServerHandle = serverHandle,
|
||||||
|
ItemHandle = itemHandle,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds multiple items to the MXAccess session in a single command.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="tagAddresses">The item tag addresses to add.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>Per-item subscription results.</returns>
|
||||||
|
public async Task<IReadOnlyList<SubscribeResult>> AddItemBulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<string> tagAddresses,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(tagAddresses);
|
||||||
|
|
||||||
|
AddItemBulkCommand command = new() { ServerHandle = serverHandle };
|
||||||
|
command.TagAddresses.Add(tagAddresses);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.AddItemBulk,
|
||||||
|
AddItemBulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.AddItemBulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Advises multiple items in a single command.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandles">The ItemHandles to advise.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>Per-item subscription results.</returns>
|
||||||
|
public async Task<IReadOnlyList<SubscribeResult>> AdviseItemBulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<int> itemHandles,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(itemHandles);
|
||||||
|
|
||||||
|
AdviseItemBulkCommand command = new() { ServerHandle = serverHandle };
|
||||||
|
command.ItemHandles.Add(itemHandles);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.AdviseItemBulk,
|
||||||
|
AdviseItemBulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.AdviseItemBulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Removes multiple items in a single command.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandles">The ItemHandles to remove.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>Per-item subscription results.</returns>
|
||||||
|
public async Task<IReadOnlyList<SubscribeResult>> RemoveItemBulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<int> itemHandles,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(itemHandles);
|
||||||
|
|
||||||
|
RemoveItemBulkCommand command = new() { ServerHandle = serverHandle };
|
||||||
|
command.ItemHandles.Add(itemHandles);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.RemoveItemBulk,
|
||||||
|
RemoveItemBulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.RemoveItemBulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Unadvises multiple items in a single command.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandles">The ItemHandles to unadvise.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>Per-item subscription results.</returns>
|
||||||
|
public async Task<IReadOnlyList<SubscribeResult>> UnAdviseItemBulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<int> itemHandles,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(itemHandles);
|
||||||
|
|
||||||
|
UnAdviseItemBulkCommand command = new() { ServerHandle = serverHandle };
|
||||||
|
command.ItemHandles.Add(itemHandles);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.UnAdviseItemBulk,
|
||||||
|
UnAdviseItemBulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.UnAdviseItemBulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds and advises multiple items in a single command.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="tagAddresses">The item tag addresses to add and advise.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>Per-item subscription results.</returns>
|
||||||
|
public async Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<string> tagAddresses,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(tagAddresses);
|
||||||
|
|
||||||
|
SubscribeBulkCommand command = new() { ServerHandle = serverHandle };
|
||||||
|
command.TagAddresses.Add(tagAddresses);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.SubscribeBulk,
|
||||||
|
SubscribeBulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.SubscribeBulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Unadvises and removes multiple items in a single command.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandles">The ItemHandles to unsubscribe.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>Per-item subscription results.</returns>
|
||||||
|
public async Task<IReadOnlyList<SubscribeResult>> UnsubscribeBulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<int> itemHandles,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(itemHandles);
|
||||||
|
|
||||||
|
UnsubscribeBulkCommand command = new() { ServerHandle = serverHandle };
|
||||||
|
command.ItemHandles.Add(itemHandles);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.UnsubscribeBulk,
|
||||||
|
UnsubscribeBulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.UnsubscribeBulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Bulk Write — sequential MXAccess Write per entry on the worker's STA.
|
||||||
|
/// Per-item failures appear as <see cref="BulkWriteResult"/> entries with
|
||||||
|
/// <c>WasSuccessful = false</c>; the call never throws on per-item errors.
|
||||||
|
/// Protocol-level failures still throw via EnsureProtocolSuccess.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="entries">Per-item write entries; each carries the item handle, value, and user id.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>One <see cref="BulkWriteResult"/> per requested entry, in request order.</returns>
|
||||||
|
public async Task<IReadOnlyList<BulkWriteResult>> WriteBulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<WriteBulkEntry> entries,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(entries);
|
||||||
|
|
||||||
|
WriteBulkCommand command = new() { ServerHandle = serverHandle };
|
||||||
|
command.Entries.Add(entries);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.WriteBulk,
|
||||||
|
WriteBulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.WriteBulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Bulk Write2 — sequential MXAccess Write2 (timestamped) per entry.
|
||||||
|
/// Per-item failures appear as <see cref="BulkWriteResult"/> entries with
|
||||||
|
/// <c>WasSuccessful = false</c>; the call never throws on per-item errors.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="entries">Per-item write entries; each carries the item handle, value, timestamp, and user id.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>One <see cref="BulkWriteResult"/> per requested entry, in request order.</returns>
|
||||||
|
public async Task<IReadOnlyList<BulkWriteResult>> Write2BulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<Write2BulkEntry> entries,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(entries);
|
||||||
|
|
||||||
|
Write2BulkCommand command = new() { ServerHandle = serverHandle };
|
||||||
|
command.Entries.Add(entries);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.Write2Bulk,
|
||||||
|
Write2Bulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.Write2Bulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Bulk WriteSecured — sequential MXAccess WriteSecured per entry.
|
||||||
|
/// Credential-sensitive values must never reach logs; the client mirrors
|
||||||
|
/// the single-item WriteSecured redaction contract.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="entries">Per-item write entries; each carries the item handle, value, current user id, and verifier user id.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>One <see cref="BulkWriteResult"/> per requested entry, in request order.</returns>
|
||||||
|
public async Task<IReadOnlyList<BulkWriteResult>> WriteSecuredBulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<WriteSecuredBulkEntry> entries,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(entries);
|
||||||
|
|
||||||
|
WriteSecuredBulkCommand command = new() { ServerHandle = serverHandle };
|
||||||
|
command.Entries.Add(entries);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.WriteSecuredBulk,
|
||||||
|
WriteSecuredBulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.WriteSecuredBulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Bulk WriteSecured2 — sequential MXAccess WriteSecured2 (timestamped) per entry.
|
||||||
|
/// Same redaction rules as <see cref="WriteSecuredBulkAsync"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="entries">Per-item write entries; each carries the item handle, value, timestamp, current user id, and verifier user id.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>One <see cref="BulkWriteResult"/> per requested entry, in request order.</returns>
|
||||||
|
public async Task<IReadOnlyList<BulkWriteResult>> WriteSecured2BulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<WriteSecured2BulkEntry> entries,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(entries);
|
||||||
|
|
||||||
|
WriteSecured2BulkCommand command = new() { ServerHandle = serverHandle };
|
||||||
|
command.Entries.Add(entries);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.WriteSecured2Bulk,
|
||||||
|
WriteSecured2Bulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.WriteSecured2Bulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Bulk Read — snapshot the current value for each requested tag.
|
||||||
|
/// Returns the cached OnDataChange value when the tag is already advised
|
||||||
|
/// (<c>WasCached = true</c>), otherwise the worker takes the full AddItem +
|
||||||
|
/// Advise + wait + UnAdvise + RemoveItem snapshot lifecycle. Per-tag
|
||||||
|
/// failures (timeout, invalid tag) appear as <see cref="BulkReadResult"/>
|
||||||
|
/// entries with <c>WasSuccessful = false</c>; the call never throws on
|
||||||
|
/// per-tag errors.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="tagAddresses">Tag addresses to read (one per result).</param>
|
||||||
|
/// <param name="timeout">Per-call timeout for the snapshot lifecycle path; <see cref="TimeSpan.Zero"/> uses the gateway default.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>One <see cref="BulkReadResult"/> per requested tag, in request order.</returns>
|
||||||
|
public async Task<IReadOnlyList<BulkReadResult>> ReadBulkAsync(
|
||||||
|
int serverHandle,
|
||||||
|
IReadOnlyList<string> tagAddresses,
|
||||||
|
TimeSpan timeout,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(tagAddresses);
|
||||||
|
|
||||||
|
ReadBulkCommand command = new()
|
||||||
|
{
|
||||||
|
ServerHandle = serverHandle,
|
||||||
|
TimeoutMs = timeout <= TimeSpan.Zero ? 0u : (uint)Math.Min(timeout.TotalMilliseconds, uint.MaxValue),
|
||||||
|
};
|
||||||
|
command.TagAddresses.Add(tagAddresses);
|
||||||
|
|
||||||
|
MxCommandReply reply = await InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.ReadBulk,
|
||||||
|
ReadBulk = command,
|
||||||
|
},
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
return reply.ReadBulk?.Results.ToArray() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes a value to an item on the MXAccess server.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
|
/// <param name="value">The value to write.</param>
|
||||||
|
/// <param name="userId">User ID context for the write.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
public async Task WriteAsync(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
MxValue value,
|
||||||
|
int userId,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
MxCommandReply reply = await WriteRawAsync(serverHandle, itemHandle, value, userId, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes a value to an item on the MXAccess server without error checking.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
|
/// <param name="value">The value to write.</param>
|
||||||
|
/// <param name="userId">User ID context for the write.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<MxCommandReply> WriteRawAsync(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
MxValue value,
|
||||||
|
int userId,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(value);
|
||||||
|
|
||||||
|
return InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.Write,
|
||||||
|
Write = new WriteCommand
|
||||||
|
{
|
||||||
|
ServerHandle = serverHandle,
|
||||||
|
ItemHandle = itemHandle,
|
||||||
|
Value = value,
|
||||||
|
UserId = userId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes a value and timestamp to an item on the MXAccess server.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
|
/// <param name="value">The value to write.</param>
|
||||||
|
/// <param name="timestampValue">The timestamp to write with the value.</param>
|
||||||
|
/// <param name="userId">User ID context for the write.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
public async Task Write2Async(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
MxValue value,
|
||||||
|
MxValue timestampValue,
|
||||||
|
int userId,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
MxCommandReply reply = await Write2RawAsync(
|
||||||
|
serverHandle,
|
||||||
|
itemHandle,
|
||||||
|
value,
|
||||||
|
timestampValue,
|
||||||
|
userId,
|
||||||
|
cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
reply.EnsureProtocolSuccess().EnsureMxAccessSuccess();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes a value and timestamp to an item on the MXAccess server without error checking.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="serverHandle">The ServerHandle from register.</param>
|
||||||
|
/// <param name="itemHandle">The ItemHandle from add-item.</param>
|
||||||
|
/// <param name="value">The value to write.</param>
|
||||||
|
/// <param name="timestampValue">The timestamp to write with the value.</param>
|
||||||
|
/// <param name="userId">User ID context for the write.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<MxCommandReply> Write2RawAsync(
|
||||||
|
int serverHandle,
|
||||||
|
int itemHandle,
|
||||||
|
MxValue value,
|
||||||
|
MxValue timestampValue,
|
||||||
|
int userId,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(value);
|
||||||
|
ArgumentNullException.ThrowIfNull(timestampValue);
|
||||||
|
|
||||||
|
return InvokeCommandAsync(
|
||||||
|
new MxCommand
|
||||||
|
{
|
||||||
|
Kind = MxCommandKind.Write2,
|
||||||
|
Write2 = new Write2Command
|
||||||
|
{
|
||||||
|
ServerHandle = serverHandle,
|
||||||
|
ItemHandle = itemHandle,
|
||||||
|
Value = value,
|
||||||
|
TimestampValue = timestampValue,
|
||||||
|
UserId = userId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Invokes an MXAccess command on this session.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The command request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>The raw server reply.</returns>
|
||||||
|
public Task<MxCommandReply> InvokeAsync(
|
||||||
|
MxCommandRequest request,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
return _client.InvokeAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Streams events from the worker for this session, optionally starting after a given sequence number.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="afterWorkerSequence">The sequence number to stream from. Defaults to 0.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token.</param>
|
||||||
|
/// <returns>An async enumerable of events.</returns>
|
||||||
|
public IAsyncEnumerable<MxEvent> StreamEventsAsync(
|
||||||
|
ulong afterWorkerSequence = 0,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
return _client.StreamEventsAsync(
|
||||||
|
new StreamEventsRequest
|
||||||
|
{
|
||||||
|
SessionId = SessionId,
|
||||||
|
AfterWorkerSequence = afterWorkerSequence,
|
||||||
|
},
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Closes the session and releases resources.
|
||||||
|
/// </summary>
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
await CloseAsync().ConfigureAwait(false);
|
||||||
|
_closeLock.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<MxCommandReply> InvokeCommandAsync(
|
||||||
|
MxCommand command,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return _client.InvokeAsync(
|
||||||
|
new MxCommandRequest
|
||||||
|
{
|
||||||
|
SessionId = SessionId,
|
||||||
|
ClientCorrelationId = Guid.NewGuid().ToString("N"),
|
||||||
|
Command = command,
|
||||||
|
},
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Exception thrown when a session is not found, not ready, or invalid.</summary>
|
||||||
|
public sealed class MxGatewaySessionException : MxGatewayException
|
||||||
|
{
|
||||||
|
/// <summary>Initializes a new instance with the given details.</summary>
|
||||||
|
/// <param name="message">The error message describing the session failure.</param>
|
||||||
|
/// <param name="sessionId">The session ID, if available.</param>
|
||||||
|
/// <param name="correlationId">The correlation ID for tracing, if available.</param>
|
||||||
|
/// <param name="protocolStatus">The protocol status details, if available.</param>
|
||||||
|
/// <param name="hResult">The HResult code, if available.</param>
|
||||||
|
/// <param name="statuses">The MXAccess statuses, if available.</param>
|
||||||
|
/// <param name="innerException">The underlying exception, if any.</param>
|
||||||
|
public MxGatewaySessionException(
|
||||||
|
string message,
|
||||||
|
string? sessionId = null,
|
||||||
|
string? correlationId = null,
|
||||||
|
ProtocolStatus? protocolStatus = null,
|
||||||
|
int? hResult = null,
|
||||||
|
IReadOnlyList<MxStatusProxy>? statuses = null,
|
||||||
|
Exception? innerException = null)
|
||||||
|
: base(
|
||||||
|
message,
|
||||||
|
sessionId,
|
||||||
|
correlationId,
|
||||||
|
protocolStatus,
|
||||||
|
hResult,
|
||||||
|
statuses ?? [],
|
||||||
|
innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Exception thrown when the worker process is unavailable or fails to process a command.</summary>
|
||||||
|
public sealed class MxGatewayWorkerException : MxGatewayException
|
||||||
|
{
|
||||||
|
/// <summary>Initializes a new instance with the given details.</summary>
|
||||||
|
/// <param name="message">The error message describing the worker failure.</param>
|
||||||
|
/// <param name="sessionId">The session ID, if available.</param>
|
||||||
|
/// <param name="correlationId">The correlation ID for tracing, if available.</param>
|
||||||
|
/// <param name="protocolStatus">The protocol status details, if available.</param>
|
||||||
|
/// <param name="hResult">The HResult code, if available.</param>
|
||||||
|
/// <param name="statuses">The MXAccess statuses, if available.</param>
|
||||||
|
/// <param name="innerException">The underlying exception, if any.</param>
|
||||||
|
public MxGatewayWorkerException(
|
||||||
|
string message,
|
||||||
|
string? sessionId = null,
|
||||||
|
string? correlationId = null,
|
||||||
|
ProtocolStatus? protocolStatus = null,
|
||||||
|
int? hResult = null,
|
||||||
|
IReadOnlyList<MxStatusProxy>? statuses = null,
|
||||||
|
Exception? innerException = null)
|
||||||
|
: base(
|
||||||
|
message,
|
||||||
|
sessionId,
|
||||||
|
correlationId,
|
||||||
|
protocolStatus,
|
||||||
|
hResult,
|
||||||
|
statuses ?? [],
|
||||||
|
innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
-2
@@ -1,9 +1,12 @@
|
|||||||
using MxGateway.Contracts.Proto;
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
|
/// <summary>Extension methods for MxStatusProxy values.</summary>
|
||||||
public static class MxStatusProxyExtensions
|
public static class MxStatusProxyExtensions
|
||||||
{
|
{
|
||||||
|
/// <summary>Returns whether the status indicates success (success flag set and category is Ok).</summary>
|
||||||
|
/// <param name="status">The status to check.</param>
|
||||||
public static bool IsSuccess(this MxStatusProxy status)
|
public static bool IsSuccess(this MxStatusProxy status)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(status);
|
ArgumentNullException.ThrowIfNull(status);
|
||||||
@@ -12,6 +15,8 @@ public static class MxStatusProxyExtensions
|
|||||||
&& status.Category is MxStatusCategory.Ok;
|
&& status.Category is MxStatusCategory.Ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns a formatted summary of the status for diagnostic output.</summary>
|
||||||
|
/// <param name="status">The status to summarize.</param>
|
||||||
public static string ToDiagnosticSummary(this MxStatusProxy status)
|
public static string ToDiagnosticSummary(this MxStatusProxy status)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(status);
|
ArgumentNullException.ThrowIfNull(status);
|
||||||
+81
-2
@@ -1,8 +1,8 @@
|
|||||||
using Google.Protobuf;
|
using Google.Protobuf;
|
||||||
using Google.Protobuf.WellKnownTypes;
|
using Google.Protobuf.WellKnownTypes;
|
||||||
using MxGateway.Contracts.Proto;
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||||
|
|
||||||
namespace MxGateway.Client;
|
namespace ZB.MOM.WW.MxGateway.Client;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Creates and projects gateway MXAccess values without hiding the raw
|
/// Creates and projects gateway MXAccess values without hiding the raw
|
||||||
@@ -10,6 +10,10 @@ namespace MxGateway.Client;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static class MxValueExtensions
|
public static class MxValueExtensions
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a boolean value to an MxValue with MxDataType.Boolean.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">Scalar boolean value to wrap.</param>
|
||||||
public static MxValue ToMxValue(this bool value)
|
public static MxValue ToMxValue(this bool value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -20,6 +24,10 @@ public static class MxValueExtensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a 32-bit integer value to an MxValue with MxDataType.Integer.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">32-bit integer value to wrap.</param>
|
||||||
public static MxValue ToMxValue(this int value)
|
public static MxValue ToMxValue(this int value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -30,6 +38,10 @@ public static class MxValueExtensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a 64-bit integer value to an MxValue with MxDataType.Integer.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">64-bit integer value to wrap.</param>
|
||||||
public static MxValue ToMxValue(this long value)
|
public static MxValue ToMxValue(this long value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -40,6 +52,10 @@ public static class MxValueExtensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a single-precision floating-point value to an MxValue with MxDataType.Float.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">Single-precision floating-point value to wrap.</param>
|
||||||
public static MxValue ToMxValue(this float value)
|
public static MxValue ToMxValue(this float value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -50,6 +66,10 @@ public static class MxValueExtensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a double-precision floating-point value to an MxValue with MxDataType.Double.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">Double-precision floating-point value to wrap.</param>
|
||||||
public static MxValue ToMxValue(this double value)
|
public static MxValue ToMxValue(this double value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -60,6 +80,10 @@ public static class MxValueExtensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a string value to an MxValue with MxDataType.String.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">String value to wrap.</param>
|
||||||
public static MxValue ToMxValue(this string value)
|
public static MxValue ToMxValue(this string value)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(value);
|
ArgumentNullException.ThrowIfNull(value);
|
||||||
@@ -72,6 +96,10 @@ public static class MxValueExtensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a DateTimeOffset value to an MxValue with MxDataType.Time.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">DateTimeOffset value to wrap.</param>
|
||||||
public static MxValue ToMxValue(this DateTimeOffset value)
|
public static MxValue ToMxValue(this DateTimeOffset value)
|
||||||
{
|
{
|
||||||
return new MxValue
|
return new MxValue
|
||||||
@@ -82,6 +110,10 @@ public static class MxValueExtensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a DateTime value to an MxValue with MxDataType.Time.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">DateTime value to wrap.</param>
|
||||||
public static MxValue ToMxValue(this DateTime value)
|
public static MxValue ToMxValue(this DateTime value)
|
||||||
{
|
{
|
||||||
return new DateTimeOffset(
|
return new DateTimeOffset(
|
||||||
@@ -91,6 +123,10 @@ public static class MxValueExtensions
|
|||||||
.ToMxValue();
|
.ToMxValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a boolean array to an MxValue with MxDataType.Boolean.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="values">Array of boolean values to wrap.</param>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<bool> values)
|
public static MxValue ToMxValue(this IReadOnlyList<bool> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -105,6 +141,10 @@ public static class MxValueExtensions
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a 32-bit integer array to an MxValue with MxDataType.Integer.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="values">Array of 32-bit integer values to wrap.</param>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<int> values)
|
public static MxValue ToMxValue(this IReadOnlyList<int> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -119,6 +159,10 @@ public static class MxValueExtensions
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a 64-bit integer array to an MxValue with MxDataType.Integer.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="values">Array of 64-bit integer values to wrap.</param>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<long> values)
|
public static MxValue ToMxValue(this IReadOnlyList<long> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -133,6 +177,10 @@ public static class MxValueExtensions
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a single-precision floating-point array to an MxValue with MxDataType.Float.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="values">Array of single-precision floating-point values to wrap.</param>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<float> values)
|
public static MxValue ToMxValue(this IReadOnlyList<float> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -147,6 +195,10 @@ public static class MxValueExtensions
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a double-precision floating-point array to an MxValue with MxDataType.Double.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="values">Array of double-precision floating-point values to wrap.</param>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<double> values)
|
public static MxValue ToMxValue(this IReadOnlyList<double> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -161,6 +213,10 @@ public static class MxValueExtensions
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a string array to an MxValue with MxDataType.String.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="values">Array of string values to wrap.</param>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<string> values)
|
public static MxValue ToMxValue(this IReadOnlyList<string> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -175,6 +231,10 @@ public static class MxValueExtensions
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a DateTimeOffset array to an MxValue with MxDataType.Time.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="values">Array of DateTimeOffset values to wrap.</param>
|
||||||
public static MxValue ToMxValue(this IReadOnlyList<DateTimeOffset> values)
|
public static MxValue ToMxValue(this IReadOnlyList<DateTimeOffset> values)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(values);
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
@@ -189,6 +249,10 @@ public static class MxValueExtensions
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the projection kind (field name) of the given MxValue's current oneof value.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">The MxValue whose oneof projection kind is returned.</param>
|
||||||
public static string GetProjectionKind(this MxValue value)
|
public static string GetProjectionKind(this MxValue value)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(value);
|
ArgumentNullException.ThrowIfNull(value);
|
||||||
@@ -208,6 +272,10 @@ public static class MxValueExtensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts an MxValue to a CLR object; returns the boxed value or null for null MxValues.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">The MxValue to convert.</param>
|
||||||
public static object? ToClrValue(this MxValue value)
|
public static object? ToClrValue(this MxValue value)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(value);
|
ArgumentNullException.ThrowIfNull(value);
|
||||||
@@ -227,6 +295,10 @@ public static class MxValueExtensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts an MxArray to a CLR array; returns null if the array does not have a known element type.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="array">The MxArray to convert.</param>
|
||||||
public static object? ToClrArrayValue(this MxArray array)
|
public static object? ToClrArrayValue(this MxArray array)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(array);
|
ArgumentNullException.ThrowIfNull(array);
|
||||||
@@ -249,6 +321,13 @@ public static class MxValueExtensions
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates an MxValue with MxDataType.Unknown from raw byte data, variant type, and diagnostic info.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">Raw byte data representing the value.</param>
|
||||||
|
/// <param name="variantType">Variant type string (e.g., "VT_BSTR").</param>
|
||||||
|
/// <param name="rawDiagnostic">Diagnostic string describing the raw value.</param>
|
||||||
|
/// <param name="rawDataType">Optional MXAccess data type override.</param>
|
||||||
public static MxValue ToRawMxValue(
|
public static MxValue ToRawMxValue(
|
||||||
byte[] value,
|
byte[] value,
|
||||||
string variantType,
|
string variantType,
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
[assembly: InternalsVisibleTo("ZB.MOM.WW.MxGateway.Client.Tests")]
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\..\src\ZB.MOM.WW.MxGateway.Contracts\ZB.MOM.WW.MxGateway.Contracts.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Grpc.Net.Client" Version="2.76.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.7" />
|
||||||
|
<PackageReference Include="Polly.Core" Version="8.6.6" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<IsPackable>true</IsPackable>
|
||||||
|
<PackageId>ZB.MOM.WW.MxGateway.Client</PackageId>
|
||||||
|
<Description>.NET 10 gRPC client for the MxAccessGateway service. Provides typed wrappers, retry, and a lazy-browse walker over the Galaxy Repository hierarchy.</Description>
|
||||||
|
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="..\README.md" Pack="true" PackagePath="\" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -6,8 +6,8 @@ Provide an idiomatic Go client module for MXAccess Gateway, plus a test CLI and
|
|||||||
unit tests. The Go client should be suitable for services and command-line
|
unit tests. The Go client should be suitable for services and command-line
|
||||||
automation.
|
automation.
|
||||||
|
|
||||||
Follow the [Go Style Guide](./style-guides/GoStyleGuide.md) for handwritten
|
Follow the [Go Style Guide](../../docs/style-guides/GoStyleGuide.md) for handwritten
|
||||||
code and the [Protobuf Style Guide](./style-guides/ProtobufStyleGuide.md) for
|
code and the [Protobuf Style Guide](../../docs/style-guides/ProtobufStyleGuide.md) for
|
||||||
generated contract inputs.
|
generated contract inputs.
|
||||||
|
|
||||||
## Module Layout
|
## Module Layout
|
||||||
@@ -74,6 +74,12 @@ func (s *Session) Unregister(ctx context.Context, serverHandle int32) error
|
|||||||
func (s *Session) AddItem(ctx context.Context, serverHandle int32, item string) (int32, error)
|
func (s *Session) AddItem(ctx context.Context, serverHandle int32, item string) (int32, error)
|
||||||
func (s *Session) AddItem2(ctx context.Context, serverHandle int32, item, context string) (int32, error)
|
func (s *Session) AddItem2(ctx context.Context, serverHandle int32, item, context string) (int32, error)
|
||||||
func (s *Session) Advise(ctx context.Context, serverHandle, itemHandle int32) error
|
func (s *Session) Advise(ctx context.Context, serverHandle, itemHandle int32) error
|
||||||
|
func (s *Session) AddItemBulk(ctx context.Context, serverHandle int32, tagAddresses []string) ([]*pb.SubscribeResult, error)
|
||||||
|
func (s *Session) AdviseItemBulk(ctx context.Context, serverHandle int32, itemHandles []int32) ([]*pb.SubscribeResult, error)
|
||||||
|
func (s *Session) RemoveItemBulk(ctx context.Context, serverHandle int32, itemHandles []int32) ([]*pb.SubscribeResult, error)
|
||||||
|
func (s *Session) UnAdviseItemBulk(ctx context.Context, serverHandle int32, itemHandles []int32) ([]*pb.SubscribeResult, error)
|
||||||
|
func (s *Session) SubscribeBulk(ctx context.Context, serverHandle int32, tagAddresses []string) ([]*pb.SubscribeResult, error)
|
||||||
|
func (s *Session) UnsubscribeBulk(ctx context.Context, serverHandle int32, itemHandles []int32) ([]*pb.SubscribeResult, error)
|
||||||
func (s *Session) Write(ctx context.Context, serverHandle, itemHandle int32, value Value, userID int32) error
|
func (s *Session) Write(ctx context.Context, serverHandle, itemHandle int32, value Value, userID int32) error
|
||||||
func (s *Session) Events(ctx context.Context) (<-chan EventResult, error)
|
func (s *Session) Events(ctx context.Context) (<-chan EventResult, error)
|
||||||
func (s *Session) Close(ctx context.Context) error
|
func (s *Session) Close(ctx context.Context) error
|
||||||
@@ -170,3 +176,10 @@ MXGATEWAY_INTEGRATION=1
|
|||||||
|
|
||||||
Integration test should run `OpenSession`, `Register`, `AddItem`, `Advise`,
|
Integration test should run `OpenSession`, `Register`, `AddItem`, `Advise`,
|
||||||
bounded `StreamEvents`, and `CloseSession`.
|
bounded `StreamEvents`, and `CloseSession`.
|
||||||
|
|
||||||
|
## Related Documentation
|
||||||
|
|
||||||
|
- [Client Libraries Detailed Design](../../docs/ClientLibrariesDesign.md)
|
||||||
|
- [Client Proto Generation](../../docs/ClientProtoGeneration.md)
|
||||||
|
- [Client Packaging](../../docs/ClientPackaging.md)
|
||||||
|
- [Go Style Guide](../../docs/style-guides/GoStyleGuide.md)
|
||||||
+237
-6
@@ -3,7 +3,7 @@
|
|||||||
The Go client module contains the generated MXAccess Gateway protobuf bindings,
|
The Go client module contains the generated MXAccess Gateway protobuf bindings,
|
||||||
a small handwritten `mxgateway` package, and the `mxgw-go` test CLI scaffold.
|
a small handwritten `mxgateway` package, and the `mxgw-go` test CLI scaffold.
|
||||||
The module uses the shared proto inputs documented in
|
The module uses the shared proto inputs documented in
|
||||||
`../../docs/client-proto-generation.md` so gateway and client contracts stay in
|
`../../docs/ClientProtoGeneration.md` so gateway and client contracts stay in
|
||||||
sync.
|
sync.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
@@ -28,7 +28,7 @@ Run generation after the shared `.proto` files or the Go output path changes:
|
|||||||
./generate-proto.ps1
|
./generate-proto.ps1
|
||||||
```
|
```
|
||||||
|
|
||||||
The script uses the tool paths recorded in `../../docs/toolchain-links.md`.
|
The script uses the tool paths recorded in `../../docs/ToolchainLinks.md`.
|
||||||
|
|
||||||
## Build And Test
|
## Build And Test
|
||||||
|
|
||||||
@@ -44,6 +44,24 @@ The tests parse the shared JSON fixtures, exercise value and status conversion,
|
|||||||
use `bufconn` for fake gateway auth and streaming behavior, and cover CLI JSON
|
use `bufconn` for fake gateway auth and streaming behavior, and cover CLI JSON
|
||||||
redaction.
|
redaction.
|
||||||
|
|
||||||
|
## Packaging
|
||||||
|
|
||||||
|
Build a local CLI executable from `clients/go`:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
New-Item -ItemType Directory -Force ../../artifacts/clients/go | Out-Null
|
||||||
|
go build -o ../../artifacts/clients/go/mxgw-go.exe ./cmd/mxgw-go
|
||||||
|
```
|
||||||
|
|
||||||
|
Install the CLI into the active `GOBIN` or `GOPATH/bin`:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
go install ./cmd/mxgw-go
|
||||||
|
```
|
||||||
|
|
||||||
|
Other Go modules can consume the library package with the module path
|
||||||
|
`gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/mxgateway`.
|
||||||
|
|
||||||
## Client API
|
## Client API
|
||||||
|
|
||||||
Use `mxgateway.Dial` with `mxgateway.Options` to configure plaintext or TLS
|
Use `mxgateway.Dial` with `mxgateway.Options` to configure plaintext or TLS
|
||||||
@@ -58,10 +76,163 @@ client, err := mxgateway.Dial(ctx, mxgateway.Options{
|
|||||||
```
|
```
|
||||||
|
|
||||||
`Client.OpenSession` returns a `Session` with helpers for `Register`,
|
`Client.OpenSession` returns a `Session` with helpers for `Register`,
|
||||||
`AddItem`, `AddItem2`, `Advise`, `Write`, `Events`, and `Close`. Raw protobuf
|
`AddItem`, `AddItem2`, `Advise`, `Write`, `Events`, and `Close`. Prefer
|
||||||
messages remain available through the `mxgateway` package aliases and the
|
`SubscribeEvents` or `SubscribeEventsAfter` for long-running streams because the
|
||||||
`Raw` helper methods. Typed errors support `errors.As` for `GatewayError`,
|
returned subscription owns cancellation and exposes `Close` for deterministic
|
||||||
`CommandError`, and `MxAccessError`; command errors preserve the raw reply.
|
goroutine cleanup. Raw protobuf messages remain available through the
|
||||||
|
`mxgateway` package aliases and the `Raw` helper methods. Typed errors support
|
||||||
|
`errors.As` for `GatewayError`, `CommandError`, and `MxAccessError`; command
|
||||||
|
errors preserve the raw reply.
|
||||||
|
|
||||||
|
For alarms, the package exposes `Client.QueryActiveAlarms` for one-shot
|
||||||
|
snapshots, `Client.StreamAlarms` for the server-streaming feed, and
|
||||||
|
`Client.AcknowledgeAlarm` to ack an alarm by full reference. The streaming
|
||||||
|
call returns a `StreamAlarmsClient`; cancel its context to terminate the
|
||||||
|
stream. All three pass straight through to the gateway's central alarm
|
||||||
|
monitor.
|
||||||
|
|
||||||
|
## Galaxy Repository browse
|
||||||
|
|
||||||
|
The `GalaxyRepository` service (proto package `galaxy_repository.v1`) is a
|
||||||
|
read-only metadata-only browse over the AVEVA System Platform Galaxy
|
||||||
|
Repository. It uses the same API-key authentication as the MXAccess Gateway
|
||||||
|
and requires the `metadata:read` scope. Use `mxgateway.DialGalaxy` to obtain a
|
||||||
|
`*GalaxyClient` that mirrors the connection-management conventions of
|
||||||
|
`Client`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
galaxy, err := mxgateway.DialGalaxy(ctx, mxgateway.Options{
|
||||||
|
Endpoint: "localhost:5000",
|
||||||
|
APIKey: os.Getenv("MXGATEWAY_API_KEY"),
|
||||||
|
Plaintext: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer galaxy.Close()
|
||||||
|
|
||||||
|
ok, err := galaxy.TestConnection(ctx)
|
||||||
|
deployTime, present, err := galaxy.GetLastDeployTime(ctx)
|
||||||
|
objects, err := galaxy.DiscoverHierarchy(ctx)
|
||||||
|
```
|
||||||
|
|
||||||
|
`GetLastDeployTime` returns `(time.Time{}, false, nil)` when the server
|
||||||
|
reports `present=false` (no deploy recorded). `DiscoverHierarchy` returns
|
||||||
|
the generated `*GalaxyObject` slice with each object's dynamic attributes
|
||||||
|
populated for direct contract access.
|
||||||
|
|
||||||
|
### Browsing lazily
|
||||||
|
|
||||||
|
For UI trees or OPC UA bridges, use `BrowseChildren` to walk one level at a
|
||||||
|
time instead of loading the full hierarchy. Pass an empty request for root
|
||||||
|
objects; subsequent calls set `ParentGobjectId`, `ParentTagName`, or
|
||||||
|
`ParentContainedPath`. Filter fields match `DiscoverHierarchy`. Each response
|
||||||
|
pairs `Children` with `ChildHasChildren` so you know which nodes to expand. See
|
||||||
|
[Galaxy Repository](../../docs/GalaxyRepository.md#browsechildren) for full
|
||||||
|
request and filter semantics.
|
||||||
|
|
||||||
|
```go
|
||||||
|
import pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated/galaxy_repository/v1"
|
||||||
|
|
||||||
|
reply, err := galaxy.BrowseChildren(ctx, &pb.BrowseChildrenRequest{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for i, child := range reply.GetChildren() {
|
||||||
|
fmt.Printf("%s expand=%v\n", child.GetTagName(), reply.GetChildHasChildren()[i])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### High-level walker
|
||||||
|
|
||||||
|
For UI trees, the client provides a `LazyBrowseNode` walker that handles
|
||||||
|
sibling pagination and the `child_has_children` hint for you:
|
||||||
|
|
||||||
|
```go
|
||||||
|
galaxy, err := mxgateway.DialGalaxy(ctx, mxgateway.Options{
|
||||||
|
Endpoint: "localhost:5000",
|
||||||
|
APIKey: os.Getenv("MXGATEWAY_API_KEY"),
|
||||||
|
Plaintext: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer galaxy.Close()
|
||||||
|
|
||||||
|
roots, err := galaxy.Browse(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, root := range roots {
|
||||||
|
if root.HasChildrenHint() {
|
||||||
|
if err := root.Expand(ctx); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, child := range root.Children() {
|
||||||
|
kind := "leaf"
|
||||||
|
if child.HasChildrenHint() {
|
||||||
|
kind = "has children"
|
||||||
|
}
|
||||||
|
fmt.Printf("%s (%s)\n", child.Object().GetTagName(), kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`Expand` is idempotent — calling it twice fires only one RPC,
|
||||||
|
and is safe under concurrent callers. To refresh after a Galaxy redeploy, call
|
||||||
|
`Browse` again from the root.
|
||||||
|
|
||||||
|
### Watching deploy events
|
||||||
|
|
||||||
|
`WatchDeployEvents` opens a server-streaming subscription. The server emits a
|
||||||
|
bootstrap event with the current Galaxy state immediately on subscribe, then
|
||||||
|
one `DeployEvent` per new deploy. `Sequence` is monotonic per server start;
|
||||||
|
gaps signal dropped events. Pass a non-nil `lastSeenDeployTime` to suppress the
|
||||||
|
bootstrap event when resuming from a known checkpoint:
|
||||||
|
|
||||||
|
```go
|
||||||
|
streamCtx, cancel := context.WithCancel(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
events, errs, err := galaxy.WatchDeployEvents(streamCtx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case ev, ok := <-events:
|
||||||
|
if !ok {
|
||||||
|
return nil // stream completed (server EOF or ctx cancelled)
|
||||||
|
}
|
||||||
|
log.Printf("seq=%d objects=%d attrs=%d",
|
||||||
|
ev.GetSequence(), ev.GetObjectCount(), ev.GetAttributeCount())
|
||||||
|
case streamErr := <-errs:
|
||||||
|
if streamErr != nil {
|
||||||
|
return streamErr // *GatewayError
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Cancel the supplied context to tear down the stream cleanly. Both channels
|
||||||
|
close after EOF, cancellation, or a terminal error; surfaced errors are wrapped
|
||||||
|
in `*GatewayError`.
|
||||||
|
|
||||||
|
The CLI exposes the same RPC via `galaxy-watch`:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
go run ./cmd/mxgw-go galaxy-watch -plaintext
|
||||||
|
go run ./cmd/mxgw-go galaxy-watch -plaintext -json
|
||||||
|
go run ./cmd/mxgw-go galaxy-watch -plaintext -last-seen-deploy-time 2026-04-28T10:00:00Z
|
||||||
|
go run ./cmd/mxgw-go galaxy-watch -plaintext -limit 5
|
||||||
|
```
|
||||||
|
|
||||||
|
The command runs until Ctrl+C (or the optional `-limit` is reached) and prints
|
||||||
|
one line per event in text mode or one JSON object per event with `-json`.
|
||||||
|
|
||||||
## CLI
|
## CLI
|
||||||
|
|
||||||
@@ -77,7 +248,67 @@ go run ./cmd/mxgw-go advise -session-id <id> -server-handle 1 -item-handle 1 -pl
|
|||||||
go run ./cmd/mxgw-go write -session-id <id> -server-handle 1 -item-handle 1 -type int32 -value 123 -plaintext -json
|
go run ./cmd/mxgw-go write -session-id <id> -server-handle 1 -item-handle 1 -type int32 -value 123 -plaintext -json
|
||||||
go run ./cmd/mxgw-go stream-events -session-id <id> -plaintext -json
|
go run ./cmd/mxgw-go stream-events -session-id <id> -plaintext -json
|
||||||
go run ./cmd/mxgw-go smoke -item Area001.Tag.Value -plaintext -json
|
go run ./cmd/mxgw-go smoke -item Area001.Tag.Value -plaintext -json
|
||||||
|
go run ./cmd/mxgw-go galaxy-test-connection -plaintext -json
|
||||||
|
go run ./cmd/mxgw-go galaxy-last-deploy -plaintext -json
|
||||||
|
go run ./cmd/mxgw-go galaxy-discover -plaintext -json
|
||||||
|
go run ./cmd/mxgw-go galaxy-watch -plaintext -json
|
||||||
```
|
```
|
||||||
|
|
||||||
Use `-api-key-env MXGATEWAY_API_KEY` or `-api-key <key>` when authentication is
|
Use `-api-key-env MXGATEWAY_API_KEY` or `-api-key <key>` when authentication is
|
||||||
enabled. CLI output redacts the key value and never writes the raw secret.
|
enabled. CLI output redacts the key value and never writes the raw secret.
|
||||||
|
|
||||||
|
Use TLS options for a secured gateway:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
go run ./cmd/mxgw-go smoke -endpoint mxgateway.example.local:5001 -ca-cert C:\certs\mxgateway-ca.pem -server-name-override mxgateway.example.local -api-key-env MXGATEWAY_API_KEY -item Area001.Tag.Value -json
|
||||||
|
```
|
||||||
|
|
||||||
|
## Integration Checks
|
||||||
|
|
||||||
|
Run live checks only when a gateway and MXAccess-backed worker are available:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:MXGATEWAY_INTEGRATION = '1'
|
||||||
|
$env:MXGATEWAY_ENDPOINT = 'localhost:5000'
|
||||||
|
$env:MXGATEWAY_API_KEY = '<gateway-api-key>'
|
||||||
|
$env:MXGATEWAY_TEST_ITEM = 'Area001.Tag.Value'
|
||||||
|
go run ./cmd/mxgw-go smoke -endpoint $env:MXGATEWAY_ENDPOINT -plaintext -api-key-env MXGATEWAY_API_KEY -item $env:MXGATEWAY_TEST_ITEM -json
|
||||||
|
```
|
||||||
|
|
||||||
|
## Installing the Go client
|
||||||
|
|
||||||
|
The module is resolved directly from the git repo — no package registry:
|
||||||
|
|
||||||
|
````bash
|
||||||
|
go get gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go@v0.1.0
|
||||||
|
````
|
||||||
|
|
||||||
|
Then import:
|
||||||
|
|
||||||
|
````go
|
||||||
|
import "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/mxgateway"
|
||||||
|
````
|
||||||
|
|
||||||
|
If your build environment cannot reach `gitea.dohertylan.com` directly,
|
||||||
|
configure `GOPROXY` to point at an internal proxy that fronts the Gitea
|
||||||
|
repo, or use `GONOSUMCHECK` + `GOPRIVATE` to bypass the checksum database
|
||||||
|
for the internal module path.
|
||||||
|
|
||||||
|
## Releasing a new version
|
||||||
|
|
||||||
|
Go modules in monorepo subdirectories use prefixed tags. To tag a release
|
||||||
|
from this repo:
|
||||||
|
|
||||||
|
````bash
|
||||||
|
pwsh scripts/tag-go-module.ps1 -Version v0.1.1 -Push
|
||||||
|
````
|
||||||
|
|
||||||
|
The script validates semver, refuses to tag with uncommitted tracked
|
||||||
|
changes, creates an annotated tag `clients/go/v0.1.1`, and (with `-Push`)
|
||||||
|
pushes it to origin.
|
||||||
|
|
||||||
|
## Related Documentation
|
||||||
|
|
||||||
|
- [Client Packaging](../../docs/ClientPackaging.md)
|
||||||
|
- [Client Proto Generation](../../docs/ClientProtoGeneration.md)
|
||||||
|
- [Go Client Detailed Design](./GoClientDesign.md)
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -2,9 +2,15 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
|
||||||
|
"google.golang.org/grpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestRunVersionJSON(t *testing.T) {
|
func TestRunVersionJSON(t *testing.T) {
|
||||||
@@ -47,6 +53,34 @@ func TestCommonOptionsRedactsAPIKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRunBatchEmitsEORAfterVersion(t *testing.T) {
|
||||||
|
var stdout bytes.Buffer
|
||||||
|
var stderr bytes.Buffer
|
||||||
|
|
||||||
|
in := strings.NewReader("version --json\n")
|
||||||
|
if err := runBatch(t.Context(), in, &stdout, &stderr); err != nil {
|
||||||
|
t.Fatalf("runBatch() error = %v; stderr = %s", err, stderr.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
out := stdout.String()
|
||||||
|
if !strings.Contains(out, "\n"+batchEOR+"\n") && !strings.HasSuffix(out, batchEOR+"\n") {
|
||||||
|
t.Fatalf("expected EOR marker %q in stdout; got: %q", batchEOR, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
idx := strings.Index(out, batchEOR)
|
||||||
|
if idx <= 0 {
|
||||||
|
t.Fatalf("EOR marker not found or appeared before any output: %q", out)
|
||||||
|
}
|
||||||
|
payload := out[:idx]
|
||||||
|
var output versionOutput
|
||||||
|
if err := json.Unmarshal([]byte(payload), &output); err != nil {
|
||||||
|
t.Fatalf("parse JSON block before EOR: %v (payload=%q)", err, payload)
|
||||||
|
}
|
||||||
|
if output.GatewayProtocolVersion == 0 || output.WorkerProtocolVersion == 0 {
|
||||||
|
t.Fatalf("protocol versions were not populated: %+v", output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestParseValueBuildsTypedValue(t *testing.T) {
|
func TestParseValueBuildsTypedValue(t *testing.T) {
|
||||||
value, err := parseValue("int32", "123")
|
value, err := parseValue("int32", "123")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -56,3 +90,207 @@ func TestParseValueBuildsTypedValue(t *testing.T) {
|
|||||||
t.Fatalf("int32 value = %d, want 123", got)
|
t.Fatalf("int32 value = %d, want 123", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRunWriteBulkVariantGatesSecuredFlags pins the Client.Go-022 fix:
|
||||||
|
// secured-only flags must be unavailable on non-secured variants, and
|
||||||
|
// vice-versa, so a wrong-variant flag fails with a clean "flag provided
|
||||||
|
// but not defined" error instead of silently no-op'ing.
|
||||||
|
func TestRunWriteBulkVariantGatesSecuredFlags(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "write-bulk-rejects-current-user-id",
|
||||||
|
args: []string{"write-bulk", "-current-user-id", "5", "-item-handles", "1", "-values", "1"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "write-bulk-rejects-verifier-user-id",
|
||||||
|
args: []string{"write-bulk", "-verifier-user-id", "5", "-item-handles", "1", "-values", "1"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "write2-bulk-rejects-current-user-id",
|
||||||
|
args: []string{"write2-bulk", "-current-user-id", "5", "-item-handles", "1", "-values", "1"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "write-secured-bulk-rejects-user-id",
|
||||||
|
args: []string{"write-secured-bulk", "-user-id", "5", "-item-handles", "1", "-values", "1"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "write-secured2-bulk-rejects-user-id",
|
||||||
|
args: []string{"write-secured2-bulk", "-user-id", "5", "-item-handles", "1", "-values", "1"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
err := runWithIO(t.Context(), tc.args, &stdout, &stderr)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("runWithIO(%v) returned no error", tc.args)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "flag provided but not defined") {
|
||||||
|
t.Fatalf("runWithIO(%v) error = %v; want 'flag provided but not defined'", tc.args, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRunBenchReadBulkRespectsContextCancellation pins the Client.Go-023
|
||||||
|
// fix: the warm-up and steady-state wall-clock loops must honour ctx.Err()
|
||||||
|
// so an external cancel (Ctrl+C, parent-cancel from a cross-language bench
|
||||||
|
// driver) short-circuits the bench instead of spinning failing ReadBulk
|
||||||
|
// calls until the wall-clock deadline elapses.
|
||||||
|
func TestRunBenchReadBulkRespectsContextCancellation(t *testing.T) {
|
||||||
|
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("listen: %v", err)
|
||||||
|
}
|
||||||
|
server := grpc.NewServer()
|
||||||
|
fake := &benchFakeGateway{}
|
||||||
|
pb.RegisterMxAccessGatewayServer(server, fake)
|
||||||
|
go func() {
|
||||||
|
_ = server.Serve(listener)
|
||||||
|
}()
|
||||||
|
defer server.Stop()
|
||||||
|
defer listener.Close()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
// Long warm-up + duration, so if the ctx.Err() guard were missing the
|
||||||
|
// loops would run for ~10s. With the guard, the cancel below short-
|
||||||
|
// circuits both loops within ~one ReadBulk iteration.
|
||||||
|
args := []string{
|
||||||
|
"bench-read-bulk",
|
||||||
|
"-endpoint", listener.Addr().String(),
|
||||||
|
"-plaintext",
|
||||||
|
"-api-key", "test",
|
||||||
|
"-warmup-seconds", "5",
|
||||||
|
"-duration-seconds", "5",
|
||||||
|
"-bulk-size", "1",
|
||||||
|
"-timeout-ms", "100",
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cancel after a brief delay — far less than warmup+duration (10s).
|
||||||
|
go func() {
|
||||||
|
time.Sleep(150 * time.Millisecond)
|
||||||
|
cancel()
|
||||||
|
}()
|
||||||
|
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
start := time.Now()
|
||||||
|
err = runWithIO(ctx, args, &stdout, &stderr)
|
||||||
|
elapsed := time.Since(start)
|
||||||
|
|
||||||
|
// With the ctx.Err() guard, the loops exit well before the wall-clock
|
||||||
|
// deadlines (warmup=5s + duration=5s = 10s). Allow generous slack for
|
||||||
|
// CI noise but assert clearly less than the un-guarded worst case.
|
||||||
|
if elapsed > 4*time.Second {
|
||||||
|
t.Fatalf("bench-read-bulk took %s after ctx cancel; want <4s (ctx.Err() guard missing?). err=%v stderr=%s", elapsed, err, stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// benchFakeGateway is a minimal MxAccessGatewayServer that satisfies the
|
||||||
|
// bench-read-bulk session-setup sequence (OpenSession + Invoke for Register
|
||||||
|
// / SubscribeBulk / ReadBulk / UnsubscribeBulk / CloseSession).
|
||||||
|
type benchFakeGateway struct {
|
||||||
|
pb.UnimplementedMxAccessGatewayServer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *benchFakeGateway) OpenSession(_ context.Context, _ *pb.OpenSessionRequest) (*pb.OpenSessionReply, error) {
|
||||||
|
return &pb.OpenSessionReply{
|
||||||
|
SessionId: "bench-session",
|
||||||
|
ProtocolStatus: &pb.ProtocolStatus{Code: pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *benchFakeGateway) CloseSession(_ context.Context, req *pb.CloseSessionRequest) (*pb.CloseSessionReply, error) {
|
||||||
|
return &pb.CloseSessionReply{
|
||||||
|
SessionId: req.GetSessionId(),
|
||||||
|
ProtocolStatus: &pb.ProtocolStatus{Code: pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *benchFakeGateway) Invoke(_ context.Context, req *pb.MxCommandRequest) (*pb.MxCommandReply, error) {
|
||||||
|
kind := req.GetCommand().GetKind()
|
||||||
|
reply := &pb.MxCommandReply{
|
||||||
|
SessionId: req.GetSessionId(),
|
||||||
|
Kind: kind,
|
||||||
|
ProtocolStatus: &pb.ProtocolStatus{Code: pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK},
|
||||||
|
}
|
||||||
|
switch kind {
|
||||||
|
case pb.MxCommandKind_MX_COMMAND_KIND_REGISTER:
|
||||||
|
reply.Payload = &pb.MxCommandReply_Register{Register: &pb.RegisterReply{ServerHandle: 1}}
|
||||||
|
case pb.MxCommandKind_MX_COMMAND_KIND_SUBSCRIBE_BULK:
|
||||||
|
reply.Payload = &pb.MxCommandReply_SubscribeBulk{SubscribeBulk: &pb.BulkSubscribeReply{
|
||||||
|
Results: []*pb.SubscribeResult{{ServerHandle: 1, ItemHandle: 1, WasSuccessful: true}},
|
||||||
|
}}
|
||||||
|
case pb.MxCommandKind_MX_COMMAND_KIND_READ_BULK:
|
||||||
|
reply.Payload = &pb.MxCommandReply_ReadBulk{ReadBulk: &pb.BulkReadReply{
|
||||||
|
Results: []*pb.BulkReadResult{{ItemHandle: 1, WasSuccessful: true, WasCached: true}},
|
||||||
|
}}
|
||||||
|
case pb.MxCommandKind_MX_COMMAND_KIND_UNSUBSCRIBE_BULK:
|
||||||
|
reply.Payload = &pb.MxCommandReply_UnsubscribeBulk{UnsubscribeBulk: &pb.BulkSubscribeReply{}}
|
||||||
|
}
|
||||||
|
return reply, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRunBenchReadBulkRejectsNonPositiveBulkSize pins the Client.Go-023-adjacent
|
||||||
|
// positivity checks so they cannot drift while resolving the cancellation finding.
|
||||||
|
func TestRunBenchReadBulkRejectsNonPositiveBulkSize(t *testing.T) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
err := runWithIO(t.Context(), []string{"bench-read-bulk", "-bulk-size", "0"}, &stdout, &stderr)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "bulk-size must be positive") {
|
||||||
|
t.Fatalf("bench-read-bulk -bulk-size 0 error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRunBatchSkipsBlankLinesAndContinuesUntilEOF pins the Client.Go-027 fix:
|
||||||
|
// a blank line in the middle of a batch session must NOT terminate the loop —
|
||||||
|
// only stdin EOF ends the session.
|
||||||
|
func TestRunBatchSkipsBlankLinesAndContinuesUntilEOF(t *testing.T) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
// version -> blank -> version (a stray blank line in the middle of a
|
||||||
|
// programmatic session).
|
||||||
|
in := strings.NewReader("version --json\n\nversion --json\n")
|
||||||
|
if err := runBatch(t.Context(), in, &stdout, &stderr); err != nil {
|
||||||
|
t.Fatalf("runBatch() error = %v; stderr = %s", err, stderr.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
out := stdout.String()
|
||||||
|
// Both version commands must have produced a result before the EOR sentinel.
|
||||||
|
if count := strings.Count(out, batchEOR); count != 2 {
|
||||||
|
t.Fatalf("EOR sentinel count = %d, want 2 (one per command, blank line skipped); out = %q", count, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRunBatchHandlesLongCommandLine pins the Client.Go-026 fix: a command
|
||||||
|
// line longer than the default bufio.Scanner token size (64 KiB) must not
|
||||||
|
// abort the batch session.
|
||||||
|
func TestRunBatchHandlesLongCommandLine(t *testing.T) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
// Build a single command line larger than 64 KiB. The command itself is
|
||||||
|
// invalid (no real session) but runBatch must still emit an EOR sentinel
|
||||||
|
// and continue to the next command rather than dropping the line on the
|
||||||
|
// floor with a bufio.ErrTooLong from the outer return.
|
||||||
|
huge := strings.Repeat("tag-with-a-reasonably-long-name-and-suffix,", 2000) + "trailing"
|
||||||
|
line := "subscribe-bulk -session-id none -items " + huge
|
||||||
|
if len(line) <= 64*1024 {
|
||||||
|
t.Fatalf("test setup error: long line length = %d, want > 64KiB", len(line))
|
||||||
|
}
|
||||||
|
in := strings.NewReader(line + "\nversion --json\n")
|
||||||
|
|
||||||
|
if err := runBatch(t.Context(), in, &stdout, &stderr); err != nil {
|
||||||
|
t.Fatalf("runBatch() error = %v; stderr = %s", err, stderr.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
out := stdout.String()
|
||||||
|
// Both commands must produce an EOR sentinel — the long line should be a
|
||||||
|
// per-command error (still emitted with EOR), then the version command
|
||||||
|
// should run normally.
|
||||||
|
if count := strings.Count(out, batchEOR); count != 2 {
|
||||||
|
t.Fatalf("EOR sentinel count = %d, want 2 (one per command, even when first is too long); out length = %d", count, len(out))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,20 +2,20 @@ Set-StrictMode -Version Latest
|
|||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
$repoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..')
|
$repoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..')
|
||||||
$protoRoot = Join-Path $repoRoot 'src\MxGateway.Contracts\Protos'
|
$protoRoot = Join-Path $repoRoot 'src\ZB.MOM.WW.MxGateway.Contracts\Protos'
|
||||||
$outputRoot = Join-Path $PSScriptRoot 'internal\generated'
|
$outputRoot = Join-Path $PSScriptRoot 'internal\generated'
|
||||||
$modulePath = 'gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated'
|
$modulePath = 'gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated'
|
||||||
$protoc = 'C:\Users\dohertj2\AppData\Local\Microsoft\WinGet\Packages\Google.Protobuf_Microsoft.Winget.Source_8wekyb3d8bbwe\bin\protoc.exe'
|
$protoc = 'C:\Users\dohertj2\AppData\Local\Microsoft\WinGet\Packages\Google.Protobuf_Microsoft.Winget.Source_8wekyb3d8bbwe\bin\protoc.exe'
|
||||||
$goPluginPath = 'C:\Users\dohertj2\go\bin'
|
$goPluginPath = 'C:\Users\dohertj2\go\bin'
|
||||||
|
|
||||||
if (-not (Test-Path $protoc)) {
|
if (-not (Test-Path $protoc)) {
|
||||||
throw "protoc was not found at $protoc. See docs/toolchain-links.md."
|
throw "protoc was not found at $protoc. See docs/ToolchainLinks.md."
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($pluginName in @('protoc-gen-go.exe', 'protoc-gen-go-grpc.exe')) {
|
foreach ($pluginName in @('protoc-gen-go.exe', 'protoc-gen-go-grpc.exe')) {
|
||||||
$pluginPath = Join-Path $goPluginPath $pluginName
|
$pluginPath = Join-Path $goPluginPath $pluginName
|
||||||
if (-not (Test-Path $pluginPath)) {
|
if (-not (Test-Path $pluginPath)) {
|
||||||
throw "$pluginName was not found at $pluginPath. See docs/toolchain-links.md."
|
throw "$pluginName was not found at $pluginPath. See docs/ToolchainLinks.md."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,13 +30,17 @@ $env:Path = "$goPluginPath;$env:Path"
|
|||||||
--go_opt=paths=source_relative `
|
--go_opt=paths=source_relative `
|
||||||
"--go_opt=Mmxaccess_gateway.proto=$modulePath;generated" `
|
"--go_opt=Mmxaccess_gateway.proto=$modulePath;generated" `
|
||||||
"--go_opt=Mmxaccess_worker.proto=$modulePath;generated" `
|
"--go_opt=Mmxaccess_worker.proto=$modulePath;generated" `
|
||||||
|
"--go_opt=Mgalaxy_repository.proto=$modulePath;generated" `
|
||||||
mxaccess_gateway.proto `
|
mxaccess_gateway.proto `
|
||||||
mxaccess_worker.proto
|
mxaccess_worker.proto `
|
||||||
|
galaxy_repository.proto
|
||||||
|
|
||||||
& $protoc `
|
& $protoc `
|
||||||
--proto_path=$protoRoot `
|
--proto_path=$protoRoot `
|
||||||
--go-grpc_out=$outputRoot `
|
--go-grpc_out=$outputRoot `
|
||||||
--go-grpc_opt=paths=source_relative `
|
--go-grpc_opt=paths=source_relative `
|
||||||
"--go-grpc_opt=Mmxaccess_gateway.proto=$modulePath;generated" `
|
"--go-grpc_opt=Mmxaccess_gateway.proto=$modulePath;generated" `
|
||||||
mxaccess_gateway.proto
|
"--go-grpc_opt=Mgalaxy_repository.proto=$modulePath;generated" `
|
||||||
|
mxaccess_gateway.proto `
|
||||||
|
galaxy_repository.proto
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,307 @@
|
|||||||
|
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// - protoc-gen-go-grpc v1.6.2
|
||||||
|
// - protoc v7.34.1
|
||||||
|
// source: galaxy_repository.proto
|
||||||
|
|
||||||
|
package generated
|
||||||
|
|
||||||
|
import (
|
||||||
|
context "context"
|
||||||
|
grpc "google.golang.org/grpc"
|
||||||
|
codes "google.golang.org/grpc/codes"
|
||||||
|
status "google.golang.org/grpc/status"
|
||||||
|
)
|
||||||
|
|
||||||
|
// This is a compile-time assertion to ensure that this generated file
|
||||||
|
// is compatible with the grpc package it is being compiled against.
|
||||||
|
// Requires gRPC-Go v1.64.0 or later.
|
||||||
|
const _ = grpc.SupportPackageIsVersion9
|
||||||
|
|
||||||
|
const (
|
||||||
|
GalaxyRepository_TestConnection_FullMethodName = "/galaxy_repository.v1.GalaxyRepository/TestConnection"
|
||||||
|
GalaxyRepository_GetLastDeployTime_FullMethodName = "/galaxy_repository.v1.GalaxyRepository/GetLastDeployTime"
|
||||||
|
GalaxyRepository_DiscoverHierarchy_FullMethodName = "/galaxy_repository.v1.GalaxyRepository/DiscoverHierarchy"
|
||||||
|
GalaxyRepository_WatchDeployEvents_FullMethodName = "/galaxy_repository.v1.GalaxyRepository/WatchDeployEvents"
|
||||||
|
GalaxyRepository_BrowseChildren_FullMethodName = "/galaxy_repository.v1.GalaxyRepository/BrowseChildren"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GalaxyRepositoryClient is the client API for GalaxyRepository service.
|
||||||
|
//
|
||||||
|
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||||
|
//
|
||||||
|
// Read-only browse over the AVEVA System Platform Galaxy Repository (ZB SQL
|
||||||
|
// database). Lets clients enumerate the deployed object hierarchy and each
|
||||||
|
// object's dynamic attributes so they know what tag references to subscribe
|
||||||
|
// to via the MxAccessGateway service.
|
||||||
|
type GalaxyRepositoryClient interface {
|
||||||
|
TestConnection(ctx context.Context, in *TestConnectionRequest, opts ...grpc.CallOption) (*TestConnectionReply, error)
|
||||||
|
GetLastDeployTime(ctx context.Context, in *GetLastDeployTimeRequest, opts ...grpc.CallOption) (*GetLastDeployTimeReply, error)
|
||||||
|
DiscoverHierarchy(ctx context.Context, in *DiscoverHierarchyRequest, opts ...grpc.CallOption) (*DiscoverHierarchyReply, error)
|
||||||
|
// Server-stream of deploy events. The server emits the current state immediately
|
||||||
|
// on subscribe (so clients can bootstrap their cache without waiting for the next
|
||||||
|
// deploy), then emits one event each time the gateway's hierarchy cache observes
|
||||||
|
// a new galaxy.time_of_last_deploy. The sequence field is monotonically
|
||||||
|
// increasing per server start; gaps indicate the per-subscriber buffer dropped
|
||||||
|
// older events because the client was too slow.
|
||||||
|
WatchDeployEvents(ctx context.Context, in *WatchDeployEventsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[DeployEvent], error)
|
||||||
|
// Returns the direct children of a parent object (or the root objects when
|
||||||
|
// `parent` is unset). Designed for OPC UA-style lazy expand: clients walk
|
||||||
|
// one level at a time instead of paging the full hierarchy. Filters mirror
|
||||||
|
// DiscoverHierarchy exactly. Backed by the same shared hierarchy cache.
|
||||||
|
BrowseChildren(ctx context.Context, in *BrowseChildrenRequest, opts ...grpc.CallOption) (*BrowseChildrenReply, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type galaxyRepositoryClient struct {
|
||||||
|
cc grpc.ClientConnInterface
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewGalaxyRepositoryClient(cc grpc.ClientConnInterface) GalaxyRepositoryClient {
|
||||||
|
return &galaxyRepositoryClient{cc}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *galaxyRepositoryClient) TestConnection(ctx context.Context, in *TestConnectionRequest, opts ...grpc.CallOption) (*TestConnectionReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(TestConnectionReply)
|
||||||
|
err := c.cc.Invoke(ctx, GalaxyRepository_TestConnection_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *galaxyRepositoryClient) GetLastDeployTime(ctx context.Context, in *GetLastDeployTimeRequest, opts ...grpc.CallOption) (*GetLastDeployTimeReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(GetLastDeployTimeReply)
|
||||||
|
err := c.cc.Invoke(ctx, GalaxyRepository_GetLastDeployTime_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *galaxyRepositoryClient) DiscoverHierarchy(ctx context.Context, in *DiscoverHierarchyRequest, opts ...grpc.CallOption) (*DiscoverHierarchyReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(DiscoverHierarchyReply)
|
||||||
|
err := c.cc.Invoke(ctx, GalaxyRepository_DiscoverHierarchy_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *galaxyRepositoryClient) WatchDeployEvents(ctx context.Context, in *WatchDeployEventsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[DeployEvent], error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
stream, err := c.cc.NewStream(ctx, &GalaxyRepository_ServiceDesc.Streams[0], GalaxyRepository_WatchDeployEvents_FullMethodName, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
x := &grpc.GenericClientStream[WatchDeployEventsRequest, DeployEvent]{ClientStream: stream}
|
||||||
|
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := x.ClientStream.CloseSend(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return x, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||||
|
type GalaxyRepository_WatchDeployEventsClient = grpc.ServerStreamingClient[DeployEvent]
|
||||||
|
|
||||||
|
func (c *galaxyRepositoryClient) BrowseChildren(ctx context.Context, in *BrowseChildrenRequest, opts ...grpc.CallOption) (*BrowseChildrenReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(BrowseChildrenReply)
|
||||||
|
err := c.cc.Invoke(ctx, GalaxyRepository_BrowseChildren_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GalaxyRepositoryServer is the server API for GalaxyRepository service.
|
||||||
|
// All implementations must embed UnimplementedGalaxyRepositoryServer
|
||||||
|
// for forward compatibility.
|
||||||
|
//
|
||||||
|
// Read-only browse over the AVEVA System Platform Galaxy Repository (ZB SQL
|
||||||
|
// database). Lets clients enumerate the deployed object hierarchy and each
|
||||||
|
// object's dynamic attributes so they know what tag references to subscribe
|
||||||
|
// to via the MxAccessGateway service.
|
||||||
|
type GalaxyRepositoryServer interface {
|
||||||
|
TestConnection(context.Context, *TestConnectionRequest) (*TestConnectionReply, error)
|
||||||
|
GetLastDeployTime(context.Context, *GetLastDeployTimeRequest) (*GetLastDeployTimeReply, error)
|
||||||
|
DiscoverHierarchy(context.Context, *DiscoverHierarchyRequest) (*DiscoverHierarchyReply, error)
|
||||||
|
// Server-stream of deploy events. The server emits the current state immediately
|
||||||
|
// on subscribe (so clients can bootstrap their cache without waiting for the next
|
||||||
|
// deploy), then emits one event each time the gateway's hierarchy cache observes
|
||||||
|
// a new galaxy.time_of_last_deploy. The sequence field is monotonically
|
||||||
|
// increasing per server start; gaps indicate the per-subscriber buffer dropped
|
||||||
|
// older events because the client was too slow.
|
||||||
|
WatchDeployEvents(*WatchDeployEventsRequest, grpc.ServerStreamingServer[DeployEvent]) error
|
||||||
|
// Returns the direct children of a parent object (or the root objects when
|
||||||
|
// `parent` is unset). Designed for OPC UA-style lazy expand: clients walk
|
||||||
|
// one level at a time instead of paging the full hierarchy. Filters mirror
|
||||||
|
// DiscoverHierarchy exactly. Backed by the same shared hierarchy cache.
|
||||||
|
BrowseChildren(context.Context, *BrowseChildrenRequest) (*BrowseChildrenReply, error)
|
||||||
|
mustEmbedUnimplementedGalaxyRepositoryServer()
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnimplementedGalaxyRepositoryServer must be embedded to have
|
||||||
|
// forward compatible implementations.
|
||||||
|
//
|
||||||
|
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||||
|
// pointer dereference when methods are called.
|
||||||
|
type UnimplementedGalaxyRepositoryServer struct{}
|
||||||
|
|
||||||
|
func (UnimplementedGalaxyRepositoryServer) TestConnection(context.Context, *TestConnectionRequest) (*TestConnectionReply, error) {
|
||||||
|
return nil, status.Error(codes.Unimplemented, "method TestConnection not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedGalaxyRepositoryServer) GetLastDeployTime(context.Context, *GetLastDeployTimeRequest) (*GetLastDeployTimeReply, error) {
|
||||||
|
return nil, status.Error(codes.Unimplemented, "method GetLastDeployTime not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedGalaxyRepositoryServer) DiscoverHierarchy(context.Context, *DiscoverHierarchyRequest) (*DiscoverHierarchyReply, error) {
|
||||||
|
return nil, status.Error(codes.Unimplemented, "method DiscoverHierarchy not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedGalaxyRepositoryServer) WatchDeployEvents(*WatchDeployEventsRequest, grpc.ServerStreamingServer[DeployEvent]) error {
|
||||||
|
return status.Error(codes.Unimplemented, "method WatchDeployEvents not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedGalaxyRepositoryServer) BrowseChildren(context.Context, *BrowseChildrenRequest) (*BrowseChildrenReply, error) {
|
||||||
|
return nil, status.Error(codes.Unimplemented, "method BrowseChildren not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedGalaxyRepositoryServer) mustEmbedUnimplementedGalaxyRepositoryServer() {}
|
||||||
|
func (UnimplementedGalaxyRepositoryServer) testEmbeddedByValue() {}
|
||||||
|
|
||||||
|
// UnsafeGalaxyRepositoryServer may be embedded to opt out of forward compatibility for this service.
|
||||||
|
// Use of this interface is not recommended, as added methods to GalaxyRepositoryServer will
|
||||||
|
// result in compilation errors.
|
||||||
|
type UnsafeGalaxyRepositoryServer interface {
|
||||||
|
mustEmbedUnimplementedGalaxyRepositoryServer()
|
||||||
|
}
|
||||||
|
|
||||||
|
func RegisterGalaxyRepositoryServer(s grpc.ServiceRegistrar, srv GalaxyRepositoryServer) {
|
||||||
|
// If the following call panics, it indicates UnimplementedGalaxyRepositoryServer was
|
||||||
|
// embedded by pointer and is nil. This will cause panics if an
|
||||||
|
// unimplemented method is ever invoked, so we test this at initialization
|
||||||
|
// time to prevent it from happening at runtime later due to I/O.
|
||||||
|
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||||
|
t.testEmbeddedByValue()
|
||||||
|
}
|
||||||
|
s.RegisterService(&GalaxyRepository_ServiceDesc, srv)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _GalaxyRepository_TestConnection_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(TestConnectionRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(GalaxyRepositoryServer).TestConnection(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: GalaxyRepository_TestConnection_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(GalaxyRepositoryServer).TestConnection(ctx, req.(*TestConnectionRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _GalaxyRepository_GetLastDeployTime_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(GetLastDeployTimeRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(GalaxyRepositoryServer).GetLastDeployTime(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: GalaxyRepository_GetLastDeployTime_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(GalaxyRepositoryServer).GetLastDeployTime(ctx, req.(*GetLastDeployTimeRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _GalaxyRepository_DiscoverHierarchy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(DiscoverHierarchyRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(GalaxyRepositoryServer).DiscoverHierarchy(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: GalaxyRepository_DiscoverHierarchy_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(GalaxyRepositoryServer).DiscoverHierarchy(ctx, req.(*DiscoverHierarchyRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _GalaxyRepository_WatchDeployEvents_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||||
|
m := new(WatchDeployEventsRequest)
|
||||||
|
if err := stream.RecvMsg(m); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return srv.(GalaxyRepositoryServer).WatchDeployEvents(m, &grpc.GenericServerStream[WatchDeployEventsRequest, DeployEvent]{ServerStream: stream})
|
||||||
|
}
|
||||||
|
|
||||||
|
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||||
|
type GalaxyRepository_WatchDeployEventsServer = grpc.ServerStreamingServer[DeployEvent]
|
||||||
|
|
||||||
|
func _GalaxyRepository_BrowseChildren_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(BrowseChildrenRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(GalaxyRepositoryServer).BrowseChildren(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: GalaxyRepository_BrowseChildren_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(GalaxyRepositoryServer).BrowseChildren(ctx, req.(*BrowseChildrenRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GalaxyRepository_ServiceDesc is the grpc.ServiceDesc for GalaxyRepository service.
|
||||||
|
// It's only intended for direct use with grpc.RegisterService,
|
||||||
|
// and not to be introspected or modified (even as a copy)
|
||||||
|
var GalaxyRepository_ServiceDesc = grpc.ServiceDesc{
|
||||||
|
ServiceName: "galaxy_repository.v1.GalaxyRepository",
|
||||||
|
HandlerType: (*GalaxyRepositoryServer)(nil),
|
||||||
|
Methods: []grpc.MethodDesc{
|
||||||
|
{
|
||||||
|
MethodName: "TestConnection",
|
||||||
|
Handler: _GalaxyRepository_TestConnection_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "GetLastDeployTime",
|
||||||
|
Handler: _GalaxyRepository_GetLastDeployTime_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "DiscoverHierarchy",
|
||||||
|
Handler: _GalaxyRepository_DiscoverHierarchy_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "BrowseChildren",
|
||||||
|
Handler: _GalaxyRepository_BrowseChildren_Handler,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Streams: []grpc.StreamDesc{
|
||||||
|
{
|
||||||
|
StreamName: "WatchDeployEvents",
|
||||||
|
Handler: _GalaxyRepository_WatchDeployEvents_Handler,
|
||||||
|
ServerStreams: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Metadata: "galaxy_repository.proto",
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
|||||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||||
// versions:
|
// versions:
|
||||||
// - protoc-gen-go-grpc v1.6.1
|
// - protoc-gen-go-grpc v1.6.2
|
||||||
// - protoc v7.34.1
|
// - protoc v7.34.1
|
||||||
// source: mxaccess_gateway.proto
|
// source: mxaccess_gateway.proto
|
||||||
|
|
||||||
@@ -19,10 +19,13 @@ import (
|
|||||||
const _ = grpc.SupportPackageIsVersion9
|
const _ = grpc.SupportPackageIsVersion9
|
||||||
|
|
||||||
const (
|
const (
|
||||||
MxAccessGateway_OpenSession_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/OpenSession"
|
MxAccessGateway_OpenSession_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/OpenSession"
|
||||||
MxAccessGateway_CloseSession_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/CloseSession"
|
MxAccessGateway_CloseSession_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/CloseSession"
|
||||||
MxAccessGateway_Invoke_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/Invoke"
|
MxAccessGateway_Invoke_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/Invoke"
|
||||||
MxAccessGateway_StreamEvents_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/StreamEvents"
|
MxAccessGateway_StreamEvents_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/StreamEvents"
|
||||||
|
MxAccessGateway_AcknowledgeAlarm_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/AcknowledgeAlarm"
|
||||||
|
MxAccessGateway_StreamAlarms_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/StreamAlarms"
|
||||||
|
MxAccessGateway_QueryActiveAlarms_FullMethodName = "/mxaccess_gateway.v1.MxAccessGateway/QueryActiveAlarms"
|
||||||
)
|
)
|
||||||
|
|
||||||
// MxAccessGatewayClient is the client API for MxAccessGateway service.
|
// MxAccessGatewayClient is the client API for MxAccessGateway service.
|
||||||
@@ -35,6 +38,22 @@ type MxAccessGatewayClient interface {
|
|||||||
CloseSession(ctx context.Context, in *CloseSessionRequest, opts ...grpc.CallOption) (*CloseSessionReply, error)
|
CloseSession(ctx context.Context, in *CloseSessionRequest, opts ...grpc.CallOption) (*CloseSessionReply, error)
|
||||||
Invoke(ctx context.Context, in *MxCommandRequest, opts ...grpc.CallOption) (*MxCommandReply, error)
|
Invoke(ctx context.Context, in *MxCommandRequest, opts ...grpc.CallOption) (*MxCommandReply, error)
|
||||||
StreamEvents(ctx context.Context, in *StreamEventsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[MxEvent], error)
|
StreamEvents(ctx context.Context, in *StreamEventsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[MxEvent], error)
|
||||||
|
AcknowledgeAlarm(ctx context.Context, in *AcknowledgeAlarmRequest, opts ...grpc.CallOption) (*AcknowledgeAlarmReply, error)
|
||||||
|
// Session-less central alarm feed. The stream opens with the current
|
||||||
|
// active-alarm snapshot (one `active_alarm` per alarm), then a single
|
||||||
|
// `snapshot_complete`, then a `transition` for every subsequent change.
|
||||||
|
// Served by the gateway's always-on alarm monitor; any number of clients
|
||||||
|
// fan out from the single monitor without opening a worker session.
|
||||||
|
StreamAlarms(ctx context.Context, in *StreamAlarmsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[AlarmFeedMessage], error)
|
||||||
|
// Point-in-time snapshot of the currently-active alarm set served from the
|
||||||
|
// gateway's always-on alarm monitor cache (session-less). Used after a
|
||||||
|
// reconnect to seed Part 9 client state, or to reconcile alarms that may
|
||||||
|
// have been missed during a transport blip. Streamed so callers can
|
||||||
|
// begin processing without buffering the full set.
|
||||||
|
// `QueryActiveAlarmsRequest.alarm_filter_prefix` optionally narrows the
|
||||||
|
// snapshot to alarms whose `alarm_full_reference` starts with the given
|
||||||
|
// prefix; an empty prefix returns the full set.
|
||||||
|
QueryActiveAlarms(ctx context.Context, in *QueryActiveAlarmsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ActiveAlarmSnapshot], error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type mxAccessGatewayClient struct {
|
type mxAccessGatewayClient struct {
|
||||||
@@ -94,6 +113,54 @@ func (c *mxAccessGatewayClient) StreamEvents(ctx context.Context, in *StreamEven
|
|||||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||||
type MxAccessGateway_StreamEventsClient = grpc.ServerStreamingClient[MxEvent]
|
type MxAccessGateway_StreamEventsClient = grpc.ServerStreamingClient[MxEvent]
|
||||||
|
|
||||||
|
func (c *mxAccessGatewayClient) AcknowledgeAlarm(ctx context.Context, in *AcknowledgeAlarmRequest, opts ...grpc.CallOption) (*AcknowledgeAlarmReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(AcknowledgeAlarmReply)
|
||||||
|
err := c.cc.Invoke(ctx, MxAccessGateway_AcknowledgeAlarm_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *mxAccessGatewayClient) StreamAlarms(ctx context.Context, in *StreamAlarmsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[AlarmFeedMessage], error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
stream, err := c.cc.NewStream(ctx, &MxAccessGateway_ServiceDesc.Streams[1], MxAccessGateway_StreamAlarms_FullMethodName, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
x := &grpc.GenericClientStream[StreamAlarmsRequest, AlarmFeedMessage]{ClientStream: stream}
|
||||||
|
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := x.ClientStream.CloseSend(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return x, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||||
|
type MxAccessGateway_StreamAlarmsClient = grpc.ServerStreamingClient[AlarmFeedMessage]
|
||||||
|
|
||||||
|
func (c *mxAccessGatewayClient) QueryActiveAlarms(ctx context.Context, in *QueryActiveAlarmsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ActiveAlarmSnapshot], error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
stream, err := c.cc.NewStream(ctx, &MxAccessGateway_ServiceDesc.Streams[2], MxAccessGateway_QueryActiveAlarms_FullMethodName, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
x := &grpc.GenericClientStream[QueryActiveAlarmsRequest, ActiveAlarmSnapshot]{ClientStream: stream}
|
||||||
|
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := x.ClientStream.CloseSend(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return x, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||||
|
type MxAccessGateway_QueryActiveAlarmsClient = grpc.ServerStreamingClient[ActiveAlarmSnapshot]
|
||||||
|
|
||||||
// MxAccessGatewayServer is the server API for MxAccessGateway service.
|
// MxAccessGatewayServer is the server API for MxAccessGateway service.
|
||||||
// All implementations must embed UnimplementedMxAccessGatewayServer
|
// All implementations must embed UnimplementedMxAccessGatewayServer
|
||||||
// for forward compatibility.
|
// for forward compatibility.
|
||||||
@@ -104,6 +171,22 @@ type MxAccessGatewayServer interface {
|
|||||||
CloseSession(context.Context, *CloseSessionRequest) (*CloseSessionReply, error)
|
CloseSession(context.Context, *CloseSessionRequest) (*CloseSessionReply, error)
|
||||||
Invoke(context.Context, *MxCommandRequest) (*MxCommandReply, error)
|
Invoke(context.Context, *MxCommandRequest) (*MxCommandReply, error)
|
||||||
StreamEvents(*StreamEventsRequest, grpc.ServerStreamingServer[MxEvent]) error
|
StreamEvents(*StreamEventsRequest, grpc.ServerStreamingServer[MxEvent]) error
|
||||||
|
AcknowledgeAlarm(context.Context, *AcknowledgeAlarmRequest) (*AcknowledgeAlarmReply, error)
|
||||||
|
// Session-less central alarm feed. The stream opens with the current
|
||||||
|
// active-alarm snapshot (one `active_alarm` per alarm), then a single
|
||||||
|
// `snapshot_complete`, then a `transition` for every subsequent change.
|
||||||
|
// Served by the gateway's always-on alarm monitor; any number of clients
|
||||||
|
// fan out from the single monitor without opening a worker session.
|
||||||
|
StreamAlarms(*StreamAlarmsRequest, grpc.ServerStreamingServer[AlarmFeedMessage]) error
|
||||||
|
// Point-in-time snapshot of the currently-active alarm set served from the
|
||||||
|
// gateway's always-on alarm monitor cache (session-less). Used after a
|
||||||
|
// reconnect to seed Part 9 client state, or to reconcile alarms that may
|
||||||
|
// have been missed during a transport blip. Streamed so callers can
|
||||||
|
// begin processing without buffering the full set.
|
||||||
|
// `QueryActiveAlarmsRequest.alarm_filter_prefix` optionally narrows the
|
||||||
|
// snapshot to alarms whose `alarm_full_reference` starts with the given
|
||||||
|
// prefix; an empty prefix returns the full set.
|
||||||
|
QueryActiveAlarms(*QueryActiveAlarmsRequest, grpc.ServerStreamingServer[ActiveAlarmSnapshot]) error
|
||||||
mustEmbedUnimplementedMxAccessGatewayServer()
|
mustEmbedUnimplementedMxAccessGatewayServer()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,6 +209,15 @@ func (UnimplementedMxAccessGatewayServer) Invoke(context.Context, *MxCommandRequ
|
|||||||
func (UnimplementedMxAccessGatewayServer) StreamEvents(*StreamEventsRequest, grpc.ServerStreamingServer[MxEvent]) error {
|
func (UnimplementedMxAccessGatewayServer) StreamEvents(*StreamEventsRequest, grpc.ServerStreamingServer[MxEvent]) error {
|
||||||
return status.Error(codes.Unimplemented, "method StreamEvents not implemented")
|
return status.Error(codes.Unimplemented, "method StreamEvents not implemented")
|
||||||
}
|
}
|
||||||
|
func (UnimplementedMxAccessGatewayServer) AcknowledgeAlarm(context.Context, *AcknowledgeAlarmRequest) (*AcknowledgeAlarmReply, error) {
|
||||||
|
return nil, status.Error(codes.Unimplemented, "method AcknowledgeAlarm not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedMxAccessGatewayServer) StreamAlarms(*StreamAlarmsRequest, grpc.ServerStreamingServer[AlarmFeedMessage]) error {
|
||||||
|
return status.Error(codes.Unimplemented, "method StreamAlarms not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedMxAccessGatewayServer) QueryActiveAlarms(*QueryActiveAlarmsRequest, grpc.ServerStreamingServer[ActiveAlarmSnapshot]) error {
|
||||||
|
return status.Error(codes.Unimplemented, "method QueryActiveAlarms not implemented")
|
||||||
|
}
|
||||||
func (UnimplementedMxAccessGatewayServer) mustEmbedUnimplementedMxAccessGatewayServer() {}
|
func (UnimplementedMxAccessGatewayServer) mustEmbedUnimplementedMxAccessGatewayServer() {}
|
||||||
func (UnimplementedMxAccessGatewayServer) testEmbeddedByValue() {}
|
func (UnimplementedMxAccessGatewayServer) testEmbeddedByValue() {}
|
||||||
|
|
||||||
@@ -212,6 +304,46 @@ func _MxAccessGateway_StreamEvents_Handler(srv interface{}, stream grpc.ServerSt
|
|||||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||||
type MxAccessGateway_StreamEventsServer = grpc.ServerStreamingServer[MxEvent]
|
type MxAccessGateway_StreamEventsServer = grpc.ServerStreamingServer[MxEvent]
|
||||||
|
|
||||||
|
func _MxAccessGateway_AcknowledgeAlarm_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(AcknowledgeAlarmRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(MxAccessGatewayServer).AcknowledgeAlarm(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: MxAccessGateway_AcknowledgeAlarm_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(MxAccessGatewayServer).AcknowledgeAlarm(ctx, req.(*AcknowledgeAlarmRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _MxAccessGateway_StreamAlarms_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||||
|
m := new(StreamAlarmsRequest)
|
||||||
|
if err := stream.RecvMsg(m); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return srv.(MxAccessGatewayServer).StreamAlarms(m, &grpc.GenericServerStream[StreamAlarmsRequest, AlarmFeedMessage]{ServerStream: stream})
|
||||||
|
}
|
||||||
|
|
||||||
|
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||||
|
type MxAccessGateway_StreamAlarmsServer = grpc.ServerStreamingServer[AlarmFeedMessage]
|
||||||
|
|
||||||
|
func _MxAccessGateway_QueryActiveAlarms_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||||
|
m := new(QueryActiveAlarmsRequest)
|
||||||
|
if err := stream.RecvMsg(m); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return srv.(MxAccessGatewayServer).QueryActiveAlarms(m, &grpc.GenericServerStream[QueryActiveAlarmsRequest, ActiveAlarmSnapshot]{ServerStream: stream})
|
||||||
|
}
|
||||||
|
|
||||||
|
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||||
|
type MxAccessGateway_QueryActiveAlarmsServer = grpc.ServerStreamingServer[ActiveAlarmSnapshot]
|
||||||
|
|
||||||
// MxAccessGateway_ServiceDesc is the grpc.ServiceDesc for MxAccessGateway service.
|
// MxAccessGateway_ServiceDesc is the grpc.ServiceDesc for MxAccessGateway service.
|
||||||
// It's only intended for direct use with grpc.RegisterService,
|
// It's only intended for direct use with grpc.RegisterService,
|
||||||
// and not to be introspected or modified (even as a copy)
|
// and not to be introspected or modified (even as a copy)
|
||||||
@@ -231,6 +363,10 @@ var MxAccessGateway_ServiceDesc = grpc.ServiceDesc{
|
|||||||
MethodName: "Invoke",
|
MethodName: "Invoke",
|
||||||
Handler: _MxAccessGateway_Invoke_Handler,
|
Handler: _MxAccessGateway_Invoke_Handler,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
MethodName: "AcknowledgeAlarm",
|
||||||
|
Handler: _MxAccessGateway_AcknowledgeAlarm_Handler,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
Streams: []grpc.StreamDesc{
|
Streams: []grpc.StreamDesc{
|
||||||
{
|
{
|
||||||
@@ -238,6 +374,16 @@ var MxAccessGateway_ServiceDesc = grpc.ServiceDesc{
|
|||||||
Handler: _MxAccessGateway_StreamEvents_Handler,
|
Handler: _MxAccessGateway_StreamEvents_Handler,
|
||||||
ServerStreams: true,
|
ServerStreams: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
StreamName: "StreamAlarms",
|
||||||
|
Handler: _MxAccessGateway_StreamAlarms_Handler,
|
||||||
|
ServerStreams: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
StreamName: "QueryActiveAlarms",
|
||||||
|
Handler: _MxAccessGateway_QueryActiveAlarms_Handler,
|
||||||
|
ServerStreams: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
Metadata: "mxaccess_gateway.proto",
|
Metadata: "mxaccess_gateway.proto",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1179,7 +1179,7 @@ const file_mxaccess_worker_proto_rawDesc = "" +
|
|||||||
"\x1eWORKER_FAULT_CATEGORY_STA_HUNG\x10\t\x12(\n" +
|
"\x1eWORKER_FAULT_CATEGORY_STA_HUNG\x10\t\x12(\n" +
|
||||||
"$WORKER_FAULT_CATEGORY_QUEUE_OVERFLOW\x10\n" +
|
"$WORKER_FAULT_CATEGORY_QUEUE_OVERFLOW\x10\n" +
|
||||||
"\x12*\n" +
|
"\x12*\n" +
|
||||||
"&WORKER_FAULT_CATEGORY_SHUTDOWN_TIMEOUT\x10\vB\x1c\xaa\x02\x19MxGateway.Contracts.Protob\x06proto3"
|
"&WORKER_FAULT_CATEGORY_SHUTDOWN_TIMEOUT\x10\vB&\xaa\x02#ZB.MOM.WW.MxGateway.Contracts.Protob\x06proto3"
|
||||||
|
|
||||||
var (
|
var (
|
||||||
file_mxaccess_worker_proto_rawDescOnce sync.Once
|
file_mxaccess_worker_proto_rawDescOnce sync.Once
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package mxgateway
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AcknowledgeAlarm acknowledges an active MXAccess alarm condition through the
|
||||||
|
// gateway. The gateway authenticates the request against the API key's
|
||||||
|
// invoke:alarm-ack scope and forwards the acknowledge to the worker's MXAccess
|
||||||
|
// session; the resulting native MxStatus is returned in the reply.
|
||||||
|
//
|
||||||
|
// Acks are idempotent — re-acking an already-acked condition is a no-op at
|
||||||
|
// the MxAccess layer.
|
||||||
|
func (c *Client) AcknowledgeAlarm(ctx context.Context, req *AcknowledgeAlarmRequest) (*AcknowledgeAlarmReply, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, errors.New("mxgateway: acknowledge alarm request is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
callCtx, cancel := c.callContext(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
reply, err := c.raw.AcknowledgeAlarm(callCtx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, &GatewayError{Op: "acknowledge alarm", Err: err}
|
||||||
|
}
|
||||||
|
if err := EnsureProtocolSuccess("acknowledge alarm", reply.GetProtocolStatus(), nil); err != nil {
|
||||||
|
return reply, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryActiveAlarms streams a snapshot of all alarms currently Active or
|
||||||
|
// ActiveAcked — the gateway's ConditionRefresh equivalent. Used after reconnect
|
||||||
|
// to seed local Part 9 state, or to reconcile alarms that may have been missed
|
||||||
|
// during a transport blip.
|
||||||
|
//
|
||||||
|
// The returned stream is owned by the caller; cancel ctx to release it.
|
||||||
|
// Optional alarm-reference prefix scoping (req.AlarmFilterPrefix) limits the
|
||||||
|
// stream to a sub-tree.
|
||||||
|
func (c *Client) QueryActiveAlarms(ctx context.Context, req *QueryActiveAlarmsRequest) (QueryActiveAlarmsClient, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, errors.New("mxgateway: query active alarms request is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
stream, err := c.raw.QueryActiveAlarms(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, &GatewayError{Op: "query active alarms", Err: err}
|
||||||
|
}
|
||||||
|
|
||||||
|
return stream, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamAlarms attaches to the gateway's central alarm feed. The stream opens
|
||||||
|
// with one AlarmFeedMessage per currently-active alarm (the ConditionRefresh
|
||||||
|
// snapshot), then a single snapshot-complete sentinel, then a transition for
|
||||||
|
// every subsequent raise / acknowledge / clear. It is served by the gateway's
|
||||||
|
// always-on alarm monitor — no worker session is opened — so any number of
|
||||||
|
// clients may attach.
|
||||||
|
//
|
||||||
|
// The returned stream is owned by the caller; cancel ctx to release it.
|
||||||
|
// Optional alarm-reference prefix scoping (req.AlarmFilterPrefix) limits the
|
||||||
|
// stream to a sub-tree.
|
||||||
|
func (c *Client) StreamAlarms(ctx context.Context, req *StreamAlarmsRequest) (StreamAlarmsClient, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, errors.New("mxgateway: stream alarms request is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
stream, err := c.raw.StreamAlarms(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, &GatewayError{Op: "stream alarms", Err: err}
|
||||||
|
}
|
||||||
|
|
||||||
|
return stream, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
package mxgateway
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
|
||||||
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
"google.golang.org/grpc/test/bufconn"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PR E.4 — pins the Go SDK surface for the new alarm RPCs:
|
||||||
|
// AcknowledgeAlarm + QueryActiveAlarms.
|
||||||
|
|
||||||
|
func TestAcknowledgeAlarmSendsRequestAndReturnsReply(t *testing.T) {
|
||||||
|
fake := &fakeGatewayWithAlarms{
|
||||||
|
acknowledgeReply: &pb.AcknowledgeAlarmReply{
|
||||||
|
CorrelationId: "corr-1",
|
||||||
|
ProtocolStatus: &pb.ProtocolStatus{
|
||||||
|
Code: pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK,
|
||||||
|
},
|
||||||
|
Status: &pb.MxStatusProxy{
|
||||||
|
Success: 1,
|
||||||
|
Category: pb.MxStatusCategory_MX_STATUS_CATEGORY_OK,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClientWithAlarms(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
reply, err := client.AcknowledgeAlarm(context.Background(), &pb.AcknowledgeAlarmRequest{
|
||||||
|
ClientCorrelationId: "corr-1",
|
||||||
|
AlarmFullReference: "Tank01.Level.HiHi",
|
||||||
|
Comment: "investigating",
|
||||||
|
OperatorUser: "alice",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("AcknowledgeAlarm() error = %v", err)
|
||||||
|
}
|
||||||
|
if reply.GetProtocolStatus().GetCode() != pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK {
|
||||||
|
t.Fatalf("protocol status = %v", reply.GetProtocolStatus().GetCode())
|
||||||
|
}
|
||||||
|
if got := fake.acknowledgeRequest.GetAlarmFullReference(); got != "Tank01.Level.HiHi" {
|
||||||
|
t.Fatalf("captured alarm reference = %q", got)
|
||||||
|
}
|
||||||
|
if got := fake.acknowledgeRequest.GetComment(); got != "investigating" {
|
||||||
|
t.Fatalf("captured comment = %q", got)
|
||||||
|
}
|
||||||
|
if got := fake.acknowledgeAuth; got != "Bearer test-api-key" {
|
||||||
|
t.Fatalf("authorization metadata = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAcknowledgeAlarmRejectsNilRequest(t *testing.T) {
|
||||||
|
fake := &fakeGatewayWithAlarms{}
|
||||||
|
client, cleanup := newBufconnClientWithAlarms(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
_, err := client.AcknowledgeAlarm(context.Background(), nil)
|
||||||
|
if err == nil || !errors.Is(err, errors.Unwrap(err)) && err.Error() != "mxgateway: acknowledge alarm request is required" {
|
||||||
|
// Accept either: the helper returned the literal sentinel, or the
|
||||||
|
// generic transport error — both prove nil was rejected.
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("AcknowledgeAlarm(nil) returned no error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAcknowledgeAlarmMapsUnauthenticated(t *testing.T) {
|
||||||
|
fake := &fakeGatewayWithAlarms{
|
||||||
|
acknowledgeError: status.Error(codes.Unauthenticated, "expired key"),
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClientWithAlarms(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
_, err := client.AcknowledgeAlarm(context.Background(), &pb.AcknowledgeAlarmRequest{
|
||||||
|
AlarmFullReference: "Tank01.Level.HiHi",
|
||||||
|
OperatorUser: "alice",
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("AcknowledgeAlarm() returned no error on Unauthenticated")
|
||||||
|
}
|
||||||
|
var gwErr *GatewayError
|
||||||
|
if !errors.As(err, &gwErr) {
|
||||||
|
t.Fatalf("error %T does not unwrap to *GatewayError", err)
|
||||||
|
}
|
||||||
|
if got, _ := status.FromError(gwErr.Err); got.Code() != codes.Unauthenticated {
|
||||||
|
t.Fatalf("inner status code = %v", got.Code())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQueryActiveAlarmsStreamsSnapshots(t *testing.T) {
|
||||||
|
fake := &fakeGatewayWithAlarms{
|
||||||
|
activeSnapshots: []*pb.ActiveAlarmSnapshot{
|
||||||
|
{
|
||||||
|
AlarmFullReference: "Tank01.Level.HiHi",
|
||||||
|
CurrentState: pb.AlarmConditionState_ALARM_CONDITION_STATE_ACTIVE,
|
||||||
|
Severity: 750,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AlarmFullReference: "Tank02.Level.HiHi",
|
||||||
|
CurrentState: pb.AlarmConditionState_ALARM_CONDITION_STATE_ACTIVE_ACKED,
|
||||||
|
Severity: 750,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClientWithAlarms(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
stream, err := client.QueryActiveAlarms(context.Background(), &pb.QueryActiveAlarmsRequest{
|
||||||
|
SessionId: "session-1",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("QueryActiveAlarms() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var received []*pb.ActiveAlarmSnapshot
|
||||||
|
for {
|
||||||
|
snap, err := stream.Recv()
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("stream.Recv() error = %v", err)
|
||||||
|
}
|
||||||
|
received = append(received, snap)
|
||||||
|
}
|
||||||
|
if len(received) != 2 {
|
||||||
|
t.Fatalf("snapshot count = %d, want 2", len(received))
|
||||||
|
}
|
||||||
|
if received[0].GetAlarmFullReference() != "Tank01.Level.HiHi" {
|
||||||
|
t.Fatalf("snapshot[0] ref = %q", received[0].GetAlarmFullReference())
|
||||||
|
}
|
||||||
|
if received[1].GetCurrentState() != pb.AlarmConditionState_ALARM_CONDITION_STATE_ACTIVE_ACKED {
|
||||||
|
t.Fatalf("snapshot[1] state = %v", received[1].GetCurrentState())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQueryActiveAlarmsPassesFilterPrefix(t *testing.T) {
|
||||||
|
fake := &fakeGatewayWithAlarms{}
|
||||||
|
client, cleanup := newBufconnClientWithAlarms(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
stream, err := client.QueryActiveAlarms(context.Background(), &pb.QueryActiveAlarmsRequest{
|
||||||
|
SessionId: "session-1",
|
||||||
|
AlarmFilterPrefix: "Tank01.",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("QueryActiveAlarms() error = %v", err)
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
_, err := stream.Recv()
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("stream.Recv() error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := fake.queryRequest.GetAlarmFilterPrefix(); got != "Tank01." {
|
||||||
|
t.Fatalf("captured filter prefix = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStreamAlarmsPassesFilterPrefixAndReceivesFeedMessages(t *testing.T) {
|
||||||
|
fake := &fakeGatewayWithAlarms{
|
||||||
|
feedMessages: []*pb.AlarmFeedMessage{
|
||||||
|
{
|
||||||
|
Payload: &pb.AlarmFeedMessage_ActiveAlarm{
|
||||||
|
ActiveAlarm: &pb.ActiveAlarmSnapshot{
|
||||||
|
AlarmFullReference: "Tank01.Level.HiHi",
|
||||||
|
CurrentState: pb.AlarmConditionState_ALARM_CONDITION_STATE_ACTIVE,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Payload: &pb.AlarmFeedMessage_SnapshotComplete{
|
||||||
|
SnapshotComplete: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClientWithAlarms(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
stream, err := client.StreamAlarms(context.Background(), &pb.StreamAlarmsRequest{
|
||||||
|
AlarmFilterPrefix: "Tank01.",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("StreamAlarms() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var received []*pb.AlarmFeedMessage
|
||||||
|
for {
|
||||||
|
msg, err := stream.Recv()
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("stream.Recv() error = %v", err)
|
||||||
|
}
|
||||||
|
received = append(received, msg)
|
||||||
|
}
|
||||||
|
if len(received) != 2 {
|
||||||
|
t.Fatalf("received count = %d, want 2", len(received))
|
||||||
|
}
|
||||||
|
if got := fake.streamRequest.GetAlarmFilterPrefix(); got != "Tank01." {
|
||||||
|
t.Fatalf("captured filter prefix = %q", got)
|
||||||
|
}
|
||||||
|
if got := fake.streamAuth; got != "Bearer test-api-key" {
|
||||||
|
t.Fatalf("stream authorization metadata = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStreamAlarmsRejectsNilRequest(t *testing.T) {
|
||||||
|
fake := &fakeGatewayWithAlarms{}
|
||||||
|
client, cleanup := newBufconnClientWithAlarms(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
if _, err := client.StreamAlarms(context.Background(), nil); err == nil {
|
||||||
|
t.Fatal("StreamAlarms(nil) returned no error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeGatewayWithAlarms struct {
|
||||||
|
pb.UnimplementedMxAccessGatewayServer
|
||||||
|
|
||||||
|
acknowledgeRequest *pb.AcknowledgeAlarmRequest
|
||||||
|
acknowledgeReply *pb.AcknowledgeAlarmReply
|
||||||
|
acknowledgeError error
|
||||||
|
acknowledgeAuth string
|
||||||
|
|
||||||
|
queryRequest *pb.QueryActiveAlarmsRequest
|
||||||
|
activeSnapshots []*pb.ActiveAlarmSnapshot
|
||||||
|
|
||||||
|
streamRequest *pb.StreamAlarmsRequest
|
||||||
|
feedMessages []*pb.AlarmFeedMessage
|
||||||
|
streamAuth string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeGatewayWithAlarms) AcknowledgeAlarm(ctx context.Context, req *pb.AcknowledgeAlarmRequest) (*pb.AcknowledgeAlarmReply, error) {
|
||||||
|
s.acknowledgeRequest = req
|
||||||
|
s.acknowledgeAuth = authorizationFromContext(ctx)
|
||||||
|
if s.acknowledgeError != nil {
|
||||||
|
return nil, s.acknowledgeError
|
||||||
|
}
|
||||||
|
if s.acknowledgeReply != nil {
|
||||||
|
return s.acknowledgeReply, nil
|
||||||
|
}
|
||||||
|
return &pb.AcknowledgeAlarmReply{
|
||||||
|
CorrelationId: req.GetClientCorrelationId(),
|
||||||
|
ProtocolStatus: &pb.ProtocolStatus{
|
||||||
|
Code: pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK,
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeGatewayWithAlarms) QueryActiveAlarms(req *pb.QueryActiveAlarmsRequest, stream grpc.ServerStreamingServer[pb.ActiveAlarmSnapshot]) error {
|
||||||
|
s.queryRequest = req
|
||||||
|
for _, snap := range s.activeSnapshots {
|
||||||
|
if err := stream.Send(snap); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeGatewayWithAlarms) StreamAlarms(req *pb.StreamAlarmsRequest, stream grpc.ServerStreamingServer[pb.AlarmFeedMessage]) error {
|
||||||
|
s.streamRequest = req
|
||||||
|
s.streamAuth = authorizationFromContext(stream.Context())
|
||||||
|
for _, msg := range s.feedMessages {
|
||||||
|
if err := stream.Send(msg); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newBufconnClientWithAlarms(t *testing.T, fake *fakeGatewayWithAlarms) (*Client, func()) {
|
||||||
|
t.Helper()
|
||||||
|
listener := bufconn.Listen(bufSize)
|
||||||
|
server := grpc.NewServer()
|
||||||
|
pb.RegisterMxAccessGatewayServer(server, fake)
|
||||||
|
go func() {
|
||||||
|
_ = server.Serve(listener)
|
||||||
|
}()
|
||||||
|
dialer := func(ctx context.Context, _ string) (net.Conn, error) {
|
||||||
|
return listener.DialContext(ctx)
|
||||||
|
}
|
||||||
|
client, err := Dial(context.Background(), Options{
|
||||||
|
Endpoint: "bufnet",
|
||||||
|
APIKey: "test-api-key",
|
||||||
|
Plaintext: true,
|
||||||
|
DialOptions: []grpc.DialOption{grpc.WithContextDialer(dialer)},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Dial() error = %v", err)
|
||||||
|
}
|
||||||
|
return client, func() {
|
||||||
|
client.Close()
|
||||||
|
server.Stop()
|
||||||
|
listener.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,14 @@
|
|||||||
|
// Package mxgateway is the Go client for the MXAccess Gateway gRPC service.
|
||||||
|
//
|
||||||
|
// The package wraps the generated gRPC contract with session-oriented helpers
|
||||||
|
// for invoking MXAccess commands, streaming events, and browsing the Galaxy
|
||||||
|
// Repository. Authentication uses an API-key bearer token attached as gRPC
|
||||||
|
// metadata on every call.
|
||||||
|
//
|
||||||
|
// Typical use opens a Client with Dial, opens a Session, invokes commands such
|
||||||
|
// as Register, AddItem, Advise, and Write, and consumes events via
|
||||||
|
// SubscribeEvents. Galaxy Repository browse RPCs are exposed through
|
||||||
|
// GalaxyClient.
|
||||||
package mxgateway
|
package mxgateway
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -184,8 +195,11 @@ func (c *Client) callContext(ctx context.Context) (context.Context, context.Canc
|
|||||||
if timeout < 0 {
|
if timeout < 0 {
|
||||||
return ctx, func() {}
|
return ctx, func() {}
|
||||||
}
|
}
|
||||||
if _, ok := ctx.Deadline(); ok {
|
if deadline, ok := ctx.Deadline(); ok {
|
||||||
return ctx, func() {}
|
timeoutDeadline := time.Now().Add(timeout)
|
||||||
|
if deadline.Before(timeoutDeadline) {
|
||||||
|
return ctx, func() {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return context.WithTimeout(ctx, timeout)
|
return context.WithTimeout(ctx, timeout)
|
||||||
}
|
}
|
||||||
@@ -216,10 +230,15 @@ func resolveTransportCredentials(opts Options) (credentials.TransportCredentials
|
|||||||
|
|
||||||
// OpenSessionOptions describes fields used to create an OpenSessionRequest.
|
// OpenSessionOptions describes fields used to create an OpenSessionRequest.
|
||||||
type OpenSessionOptions struct {
|
type OpenSessionOptions struct {
|
||||||
RequestedBackend string
|
// RequestedBackend selects the gateway worker backend (empty for default).
|
||||||
ClientSessionName string
|
RequestedBackend string
|
||||||
|
// ClientSessionName is a human-readable name recorded on the session.
|
||||||
|
ClientSessionName string
|
||||||
|
// ClientCorrelationID echoes through gateway logs and replies for tracing.
|
||||||
ClientCorrelationID string
|
ClientCorrelationID string
|
||||||
CommandTimeout time.Duration
|
// CommandTimeout sets the per-command timeout the gateway forwards to the
|
||||||
|
// worker; zero leaves the gateway default in place.
|
||||||
|
CommandTimeout time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
// Request returns the raw protobuf OpenSessionRequest for these options.
|
// Request returns the raw protobuf OpenSessionRequest for these options.
|
||||||
|
|||||||
@@ -77,6 +77,76 @@ func TestStreamEventsAttachesAuthMetadataAndClosesOnCancellation(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEventSubscriptionCloseStopsStream(t *testing.T) {
|
||||||
|
fake := &fakeGatewayServer{
|
||||||
|
streamStarted: make(chan struct{}),
|
||||||
|
streamDone: make(chan struct{}),
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
session := NewSessionForID(client, "session-1")
|
||||||
|
|
||||||
|
subscription, err := session.SubscribeEvents(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("SubscribeEvents() error = %v", err)
|
||||||
|
}
|
||||||
|
<-fake.streamStarted
|
||||||
|
first := <-subscription.Events()
|
||||||
|
if first.Err != nil {
|
||||||
|
t.Fatalf("first event error = %v", first.Err)
|
||||||
|
}
|
||||||
|
|
||||||
|
subscription.Close()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-fake.streamDone:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("event stream did not stop after subscription close")
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case _, ok := <-subscription.Events():
|
||||||
|
if ok {
|
||||||
|
t.Fatal("subscription channel remained open after close")
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("subscription channel did not close")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEventsAfterCancelsStreamWhenCompatibilityChannelIsAbandoned(t *testing.T) {
|
||||||
|
fake := &fakeGatewayServer{
|
||||||
|
streamStarted: make(chan struct{}),
|
||||||
|
streamDone: make(chan struct{}),
|
||||||
|
streamEventCount: 64,
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
session := NewSessionForID(client, "session-1")
|
||||||
|
|
||||||
|
events, err := session.EventsAfter(context.Background(), 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("EventsAfter() error = %v", err)
|
||||||
|
}
|
||||||
|
<-fake.streamStarted
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-fake.streamDone:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("compatibility event stream did not stop after result channel filled")
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case _, ok := <-events:
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("compatibility event channel did not close")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestSessionHelpersBuildCommandsAndExposeRawReply(t *testing.T) {
|
func TestSessionHelpersBuildCommandsAndExposeRawReply(t *testing.T) {
|
||||||
fake := &fakeGatewayServer{
|
fake := &fakeGatewayServer{
|
||||||
invokeReply: &pb.MxCommandReply{
|
invokeReply: &pb.MxCommandReply{
|
||||||
@@ -117,6 +187,249 @@ func TestSessionHelpersBuildCommandsAndExposeRawReply(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSubscribeBulkBuildsOneBulkCommandAndReturnsResults(t *testing.T) {
|
||||||
|
fake := &fakeGatewayServer{
|
||||||
|
invokeReply: &pb.MxCommandReply{
|
||||||
|
SessionId: "session-1",
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_SUBSCRIBE_BULK,
|
||||||
|
ProtocolStatus: &pb.ProtocolStatus{
|
||||||
|
Code: pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK,
|
||||||
|
},
|
||||||
|
Payload: &pb.MxCommandReply_SubscribeBulk{
|
||||||
|
SubscribeBulk: &pb.BulkSubscribeReply{
|
||||||
|
Results: []*pb.SubscribeResult{
|
||||||
|
{
|
||||||
|
ServerHandle: 12,
|
||||||
|
TagAddress: "Area001.Pump001.Speed",
|
||||||
|
ItemHandle: 34,
|
||||||
|
WasSuccessful: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
session := NewSessionForID(client, "session-1")
|
||||||
|
|
||||||
|
results, err := session.SubscribeBulk(context.Background(), 12, []string{"Area001.Pump001.Speed"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("SubscribeBulk() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(results) != 1 || results[0].GetItemHandle() != 34 {
|
||||||
|
t.Fatalf("results = %#v, want item handle 34", results)
|
||||||
|
}
|
||||||
|
req := fake.invokeRequest
|
||||||
|
if req.GetCommand().GetKind() != pb.MxCommandKind_MX_COMMAND_KIND_SUBSCRIBE_BULK {
|
||||||
|
t.Fatalf("command kind = %s", req.GetCommand().GetKind())
|
||||||
|
}
|
||||||
|
if got := req.GetCommand().GetSubscribeBulk().GetTagAddresses(); len(got) != 1 || got[0] != "Area001.Pump001.Speed" {
|
||||||
|
t.Fatalf("tag addresses = %#v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteBulkBuildsOneBulkCommandAndReturnsPerEntryResults(t *testing.T) {
|
||||||
|
fake := &fakeGatewayServer{
|
||||||
|
invokeReply: &pb.MxCommandReply{
|
||||||
|
SessionId: "session-1",
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_WRITE_BULK,
|
||||||
|
ProtocolStatus: &pb.ProtocolStatus{
|
||||||
|
Code: pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK,
|
||||||
|
},
|
||||||
|
Payload: &pb.MxCommandReply_WriteBulk{
|
||||||
|
WriteBulk: &pb.BulkWriteReply{
|
||||||
|
Results: []*pb.BulkWriteResult{
|
||||||
|
{ItemHandle: 10, WasSuccessful: true},
|
||||||
|
{ItemHandle: 11, WasSuccessful: true},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
session := NewSessionForID(client, "session-1")
|
||||||
|
|
||||||
|
entries := []*WriteBulkEntry{
|
||||||
|
{ItemHandle: 10, Value: Int32Value(7), UserId: 100},
|
||||||
|
{ItemHandle: 11, Value: Int32Value(8), UserId: 100},
|
||||||
|
}
|
||||||
|
results, err := session.WriteBulk(context.Background(), 12, entries)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("WriteBulk() error = %v", err)
|
||||||
|
}
|
||||||
|
if len(results) != 2 {
|
||||||
|
t.Fatalf("results len = %d, want 2", len(results))
|
||||||
|
}
|
||||||
|
req := fake.invokeRequest
|
||||||
|
if req.GetCommand().GetKind() != pb.MxCommandKind_MX_COMMAND_KIND_WRITE_BULK {
|
||||||
|
t.Fatalf("command kind = %s", req.GetCommand().GetKind())
|
||||||
|
}
|
||||||
|
if got := req.GetCommand().GetWriteBulk().GetEntries(); len(got) != 2 {
|
||||||
|
t.Fatalf("entry count = %d, want 2", len(got))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteBulkRejectsNilEntries(t *testing.T) {
|
||||||
|
fake := &fakeGatewayServer{}
|
||||||
|
client, cleanup := newBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
session := NewSessionForID(client, "session-1")
|
||||||
|
|
||||||
|
if _, err := session.WriteBulk(context.Background(), 12, nil); err == nil {
|
||||||
|
t.Fatal("WriteBulk(nil) returned no error")
|
||||||
|
}
|
||||||
|
if _, err := session.Write2Bulk(context.Background(), 12, nil); err == nil {
|
||||||
|
t.Fatal("Write2Bulk(nil) returned no error")
|
||||||
|
}
|
||||||
|
if _, err := session.WriteSecuredBulk(context.Background(), 12, nil); err == nil {
|
||||||
|
t.Fatal("WriteSecuredBulk(nil) returned no error")
|
||||||
|
}
|
||||||
|
if _, err := session.WriteSecured2Bulk(context.Background(), 12, nil); err == nil {
|
||||||
|
t.Fatal("WriteSecured2Bulk(nil) returned no error")
|
||||||
|
}
|
||||||
|
if _, err := session.ReadBulk(context.Background(), 12, nil, 0); err == nil {
|
||||||
|
t.Fatal("ReadBulk(nil) returned no error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBulkMethodsShortCircuitOnEmptySliceWithoutRoundTrip(t *testing.T) {
|
||||||
|
fake := &fakeGatewayServer{
|
||||||
|
invokeReply: &pb.MxCommandReply{
|
||||||
|
ProtocolStatus: &pb.ProtocolStatus{
|
||||||
|
Code: pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
session := NewSessionForID(client, "session-1")
|
||||||
|
|
||||||
|
results, err := session.WriteBulk(context.Background(), 12, []*WriteBulkEntry{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("WriteBulk(empty) error = %v", err)
|
||||||
|
}
|
||||||
|
if len(results) != 0 {
|
||||||
|
t.Fatalf("WriteBulk(empty) results len = %d, want 0", len(results))
|
||||||
|
}
|
||||||
|
if fake.invokeRequest != nil {
|
||||||
|
t.Fatal("WriteBulk(empty) sent a round trip; expected short-circuit")
|
||||||
|
}
|
||||||
|
|
||||||
|
results2, err := session.Write2Bulk(context.Background(), 12, []*Write2BulkEntry{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Write2Bulk(empty) error = %v", err)
|
||||||
|
}
|
||||||
|
if len(results2) != 0 {
|
||||||
|
t.Fatalf("Write2Bulk(empty) results len = %d, want 0", len(results2))
|
||||||
|
}
|
||||||
|
if fake.invokeRequest != nil {
|
||||||
|
t.Fatal("Write2Bulk(empty) sent a round trip; expected short-circuit")
|
||||||
|
}
|
||||||
|
|
||||||
|
results3, err := session.WriteSecuredBulk(context.Background(), 12, []*WriteSecuredBulkEntry{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("WriteSecuredBulk(empty) error = %v", err)
|
||||||
|
}
|
||||||
|
if len(results3) != 0 {
|
||||||
|
t.Fatalf("WriteSecuredBulk(empty) results len = %d, want 0", len(results3))
|
||||||
|
}
|
||||||
|
if fake.invokeRequest != nil {
|
||||||
|
t.Fatal("WriteSecuredBulk(empty) sent a round trip; expected short-circuit")
|
||||||
|
}
|
||||||
|
|
||||||
|
results4, err := session.WriteSecured2Bulk(context.Background(), 12, []*WriteSecured2BulkEntry{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("WriteSecured2Bulk(empty) error = %v", err)
|
||||||
|
}
|
||||||
|
if len(results4) != 0 {
|
||||||
|
t.Fatalf("WriteSecured2Bulk(empty) results len = %d, want 0", len(results4))
|
||||||
|
}
|
||||||
|
if fake.invokeRequest != nil {
|
||||||
|
t.Fatal("WriteSecured2Bulk(empty) sent a round trip; expected short-circuit")
|
||||||
|
}
|
||||||
|
|
||||||
|
readResults, err := session.ReadBulk(context.Background(), 12, []string{}, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ReadBulk(empty) error = %v", err)
|
||||||
|
}
|
||||||
|
if len(readResults) != 0 {
|
||||||
|
t.Fatalf("ReadBulk(empty) results len = %d, want 0", len(readResults))
|
||||||
|
}
|
||||||
|
if fake.invokeRequest != nil {
|
||||||
|
t.Fatal("ReadBulk(empty) sent a round trip; expected short-circuit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadBulkForwardsTimeoutAndUnpacksCachedFlag(t *testing.T) {
|
||||||
|
fake := &fakeGatewayServer{
|
||||||
|
invokeReply: &pb.MxCommandReply{
|
||||||
|
SessionId: "session-1",
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_READ_BULK,
|
||||||
|
ProtocolStatus: &pb.ProtocolStatus{
|
||||||
|
Code: pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK,
|
||||||
|
},
|
||||||
|
Payload: &pb.MxCommandReply_ReadBulk{
|
||||||
|
ReadBulk: &pb.BulkReadReply{
|
||||||
|
Results: []*pb.BulkReadResult{
|
||||||
|
{TagAddress: "Tank01.Level", WasSuccessful: true, WasCached: true},
|
||||||
|
{TagAddress: "Tank02.Level", WasSuccessful: true, WasCached: false},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
session := NewSessionForID(client, "session-1")
|
||||||
|
|
||||||
|
results, err := session.ReadBulk(context.Background(), 12, []string{"Tank01.Level", "Tank02.Level"}, 250*time.Millisecond)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ReadBulk() error = %v", err)
|
||||||
|
}
|
||||||
|
if len(results) != 2 {
|
||||||
|
t.Fatalf("results len = %d, want 2", len(results))
|
||||||
|
}
|
||||||
|
if !results[0].GetWasCached() || results[1].GetWasCached() {
|
||||||
|
t.Fatalf("WasCached flags = [%v %v], want [true false]", results[0].GetWasCached(), results[1].GetWasCached())
|
||||||
|
}
|
||||||
|
req := fake.invokeRequest
|
||||||
|
if req.GetCommand().GetKind() != pb.MxCommandKind_MX_COMMAND_KIND_READ_BULK {
|
||||||
|
t.Fatalf("command kind = %s", req.GetCommand().GetKind())
|
||||||
|
}
|
||||||
|
if got := req.GetCommand().GetReadBulk().GetTimeoutMs(); got != 250 {
|
||||||
|
t.Fatalf("timeout ms = %d, want 250", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadBulkSaturatesTimeoutAboveMaxUint32(t *testing.T) {
|
||||||
|
fake := &fakeGatewayServer{
|
||||||
|
invokeReply: &pb.MxCommandReply{
|
||||||
|
SessionId: "session-1",
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_READ_BULK,
|
||||||
|
ProtocolStatus: &pb.ProtocolStatus{
|
||||||
|
Code: pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
session := NewSessionForID(client, "session-1")
|
||||||
|
|
||||||
|
// 100 days in milliseconds exceeds MaxUint32 (~49.7 days).
|
||||||
|
hugeTimeout := 100 * 24 * time.Hour
|
||||||
|
_, err := session.ReadBulk(context.Background(), 12, []string{"Tank01.Level"}, hugeTimeout)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ReadBulk() error = %v", err)
|
||||||
|
}
|
||||||
|
got := fake.invokeRequest.GetCommand().GetReadBulk().GetTimeoutMs()
|
||||||
|
if got != ^uint32(0) {
|
||||||
|
t.Fatalf("timeout ms = %d, want %d (MaxUint32)", got, ^uint32(0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestInvokeReturnsTypedMxAccessErrorWithRawReply(t *testing.T) {
|
func TestInvokeReturnsTypedMxAccessErrorWithRawReply(t *testing.T) {
|
||||||
hresult := int32(-2147467259)
|
hresult := int32(-2147467259)
|
||||||
fake := &fakeGatewayServer{
|
fake := &fakeGatewayServer{
|
||||||
@@ -188,12 +501,14 @@ func newBufconnClient(t *testing.T, fake *fakeGatewayServer) (*Client, func()) {
|
|||||||
type fakeGatewayServer struct {
|
type fakeGatewayServer struct {
|
||||||
pb.UnimplementedMxAccessGatewayServer
|
pb.UnimplementedMxAccessGatewayServer
|
||||||
|
|
||||||
openReply *pb.OpenSessionReply
|
openReply *pb.OpenSessionReply
|
||||||
openAuth string
|
openAuth string
|
||||||
streamAuth string
|
streamAuth string
|
||||||
streamStarted chan struct{}
|
streamStarted chan struct{}
|
||||||
invokeReply *pb.MxCommandReply
|
streamDone chan struct{}
|
||||||
invokeRequest *pb.MxCommandRequest
|
streamEventCount int
|
||||||
|
invokeReply *pb.MxCommandReply
|
||||||
|
invokeRequest *pb.MxCommandRequest
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *fakeGatewayServer) OpenSession(ctx context.Context, req *pb.OpenSessionRequest) (*pb.OpenSessionReply, error) {
|
func (s *fakeGatewayServer) OpenSession(ctx context.Context, req *pb.OpenSessionRequest) (*pb.OpenSessionReply, error) {
|
||||||
@@ -234,15 +549,24 @@ func (s *fakeGatewayServer) Invoke(ctx context.Context, req *pb.MxCommandRequest
|
|||||||
|
|
||||||
func (s *fakeGatewayServer) StreamEvents(req *pb.StreamEventsRequest, stream grpc.ServerStreamingServer[pb.MxEvent]) error {
|
func (s *fakeGatewayServer) StreamEvents(req *pb.StreamEventsRequest, stream grpc.ServerStreamingServer[pb.MxEvent]) error {
|
||||||
s.streamAuth = authorizationFromContext(stream.Context())
|
s.streamAuth = authorizationFromContext(stream.Context())
|
||||||
|
if s.streamDone != nil {
|
||||||
|
defer close(s.streamDone)
|
||||||
|
}
|
||||||
if s.streamStarted != nil {
|
if s.streamStarted != nil {
|
||||||
close(s.streamStarted)
|
close(s.streamStarted)
|
||||||
}
|
}
|
||||||
if err := stream.Send(&pb.MxEvent{
|
eventCount := s.streamEventCount
|
||||||
SessionId: req.GetSessionId(),
|
if eventCount == 0 {
|
||||||
Family: pb.MxEventFamily_MX_EVENT_FAMILY_ON_DATA_CHANGE,
|
eventCount = 1
|
||||||
WorkerSequence: 1,
|
}
|
||||||
}); err != nil {
|
for sequence := 1; sequence <= eventCount; sequence++ {
|
||||||
return err
|
if err := stream.Send(&pb.MxEvent{
|
||||||
|
SessionId: req.GetSessionId(),
|
||||||
|
Family: pb.MxEventFamily_MX_EVENT_FAMILY_ON_DATA_CHANGE,
|
||||||
|
WorkerSequence: uint64(sequence),
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
<-stream.Context().Done()
|
<-stream.Context().Done()
|
||||||
return io.EOF
|
return io.EOF
|
||||||
|
|||||||
@@ -8,10 +8,13 @@ import (
|
|||||||
|
|
||||||
// GatewayError wraps transport-level gRPC failures.
|
// GatewayError wraps transport-level gRPC failures.
|
||||||
type GatewayError struct {
|
type GatewayError struct {
|
||||||
Op string
|
// Op names the operation that failed (for example "dial" or "invoke").
|
||||||
|
Op string
|
||||||
|
// Err is the underlying gRPC or transport error.
|
||||||
Err error
|
Err error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Error returns the formatted gateway error message.
|
||||||
func (e *GatewayError) Error() string {
|
func (e *GatewayError) Error() string {
|
||||||
if e == nil {
|
if e == nil {
|
||||||
return ""
|
return ""
|
||||||
@@ -22,6 +25,7 @@ func (e *GatewayError) Error() string {
|
|||||||
return fmt.Sprintf("mxgateway: %s failed: %v", e.Op, e.Err)
|
return fmt.Sprintf("mxgateway: %s failed: %v", e.Op, e.Err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Unwrap returns the wrapped transport error.
|
||||||
func (e *GatewayError) Unwrap() error {
|
func (e *GatewayError) Unwrap() error {
|
||||||
if e == nil {
|
if e == nil {
|
||||||
return nil
|
return nil
|
||||||
@@ -32,11 +36,15 @@ func (e *GatewayError) Unwrap() error {
|
|||||||
// CommandError reports a non-OK gateway protocol status and keeps the raw
|
// CommandError reports a non-OK gateway protocol status and keeps the raw
|
||||||
// command reply when one exists.
|
// command reply when one exists.
|
||||||
type CommandError struct {
|
type CommandError struct {
|
||||||
Op string
|
// Op names the gateway operation that produced the non-OK status.
|
||||||
|
Op string
|
||||||
|
// Status carries the gateway-reported protocol status.
|
||||||
Status *ProtocolStatus
|
Status *ProtocolStatus
|
||||||
Reply *MxCommandReply
|
// Reply is the raw command reply, when one was returned alongside the status.
|
||||||
|
Reply *MxCommandReply
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Error returns the formatted command error message.
|
||||||
func (e *CommandError) Error() string {
|
func (e *CommandError) Error() string {
|
||||||
if e == nil {
|
if e == nil {
|
||||||
return ""
|
return ""
|
||||||
@@ -53,10 +61,13 @@ func (e *CommandError) Error() string {
|
|||||||
|
|
||||||
// MxAccessError reports HRESULT or MXSTATUS_PROXY failures returned by MXAccess.
|
// MxAccessError reports HRESULT or MXSTATUS_PROXY failures returned by MXAccess.
|
||||||
type MxAccessError struct {
|
type MxAccessError struct {
|
||||||
|
// Command is the wrapped CommandError when the protocol status carried one.
|
||||||
Command *CommandError
|
Command *CommandError
|
||||||
Reply *MxCommandReply
|
// Reply is the raw MXAccess command reply that surfaced the failure.
|
||||||
|
Reply *MxCommandReply
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Error returns the formatted MXAccess error message.
|
||||||
func (e *MxAccessError) Error() string {
|
func (e *MxAccessError) Error() string {
|
||||||
if e == nil {
|
if e == nil {
|
||||||
return ""
|
return ""
|
||||||
@@ -73,6 +84,7 @@ func (e *MxAccessError) Error() string {
|
|||||||
return "mxgateway: MXAccess command failed"
|
return "mxgateway: MXAccess command failed"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Unwrap returns the wrapped CommandError, when one is present.
|
||||||
func (e *MxAccessError) Unwrap() error {
|
func (e *MxAccessError) Unwrap() error {
|
||||||
if e == nil {
|
if e == nil {
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -0,0 +1,489 @@
|
|||||||
|
package mxgateway
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
|
||||||
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
"google.golang.org/protobuf/types/known/timestamppb"
|
||||||
|
)
|
||||||
|
|
||||||
|
// browseChildrenPageSize is the per-request page size used by the lazy walker.
|
||||||
|
const browseChildrenPageSize = 500
|
||||||
|
|
||||||
|
// discoverHierarchyPageSize is the per-request page size used by DiscoverHierarchy.
|
||||||
|
// Mirrors the .NET client constant so large galaxies are not silently truncated
|
||||||
|
// by the server's default page cap.
|
||||||
|
const discoverHierarchyPageSize = 5000
|
||||||
|
|
||||||
|
// RawGalaxyRepositoryClient is the generated gRPC client interface for the
|
||||||
|
// Galaxy Repository service exposed for callers that need direct contract
|
||||||
|
// access.
|
||||||
|
type RawGalaxyRepositoryClient = pb.GalaxyRepositoryClient
|
||||||
|
|
||||||
|
// Generated protobuf aliases for Galaxy Repository messages.
|
||||||
|
type (
|
||||||
|
// TestConnectionRequest is the request for Galaxy Repository TestConnection.
|
||||||
|
TestConnectionRequest = pb.TestConnectionRequest
|
||||||
|
// TestConnectionReply is the reply for Galaxy Repository TestConnection.
|
||||||
|
TestConnectionReply = pb.TestConnectionReply
|
||||||
|
// GetLastDeployTimeRequest is the request for GetLastDeployTime.
|
||||||
|
GetLastDeployTimeRequest = pb.GetLastDeployTimeRequest
|
||||||
|
// GetLastDeployTimeReply is the reply for GetLastDeployTime.
|
||||||
|
GetLastDeployTimeReply = pb.GetLastDeployTimeReply
|
||||||
|
// DiscoverHierarchyRequest is the request for DiscoverHierarchy.
|
||||||
|
DiscoverHierarchyRequest = pb.DiscoverHierarchyRequest
|
||||||
|
// DiscoverHierarchyReply is the reply for DiscoverHierarchy.
|
||||||
|
DiscoverHierarchyReply = pb.DiscoverHierarchyReply
|
||||||
|
// GalaxyObject describes one Galaxy object with its dynamic attributes.
|
||||||
|
GalaxyObject = pb.GalaxyObject
|
||||||
|
// GalaxyAttribute describes one dynamic attribute on a GalaxyObject.
|
||||||
|
GalaxyAttribute = pb.GalaxyAttribute
|
||||||
|
// WatchDeployEventsRequest is the request for WatchDeployEvents.
|
||||||
|
WatchDeployEventsRequest = pb.WatchDeployEventsRequest
|
||||||
|
// DeployEvent is one Galaxy Repository deploy event.
|
||||||
|
DeployEvent = pb.DeployEvent
|
||||||
|
// BrowseChildrenRequest is the request for BrowseChildren.
|
||||||
|
BrowseChildrenRequest = pb.BrowseChildrenRequest
|
||||||
|
// BrowseChildrenReply is the reply for BrowseChildren.
|
||||||
|
BrowseChildrenReply = pb.BrowseChildrenReply
|
||||||
|
)
|
||||||
|
|
||||||
|
// RawDeployEventStream is the generated WatchDeployEvents client stream.
|
||||||
|
type RawDeployEventStream = grpc.ServerStreamingClient[pb.DeployEvent]
|
||||||
|
|
||||||
|
// GalaxyClient owns a gateway gRPC connection and exposes Galaxy Repository
|
||||||
|
// browse helpers. It mirrors the structure of Client and uses the same
|
||||||
|
// connection-management conventions.
|
||||||
|
type GalaxyClient struct {
|
||||||
|
conn *grpc.ClientConn
|
||||||
|
raw pb.GalaxyRepositoryClient
|
||||||
|
opts Options
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialGalaxy opens a gRPC connection to the gateway for the Galaxy Repository
|
||||||
|
// service. It applies the same authentication metadata, transport security,
|
||||||
|
// and dial-timeout behavior as Dial.
|
||||||
|
func DialGalaxy(ctx context.Context, opts Options) (*GalaxyClient, error) {
|
||||||
|
if opts.Endpoint == "" {
|
||||||
|
return nil, errors.New("mxgateway: endpoint is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
dialCtx := ctx
|
||||||
|
cancel := func() {}
|
||||||
|
if opts.DialTimeout > 0 {
|
||||||
|
dialCtx, cancel = context.WithTimeout(ctx, opts.DialTimeout)
|
||||||
|
} else if _, ok := ctx.Deadline(); !ok {
|
||||||
|
dialCtx, cancel = context.WithTimeout(ctx, defaultDialTimeout)
|
||||||
|
}
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
transportCredentials, err := resolveTransportCredentials(opts)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dialOptions := []grpc.DialOption{
|
||||||
|
grpc.WithTransportCredentials(transportCredentials),
|
||||||
|
grpc.WithUnaryInterceptor(unaryAuthInterceptor(opts.APIKey)),
|
||||||
|
grpc.WithStreamInterceptor(streamAuthInterceptor(opts.APIKey)),
|
||||||
|
grpc.WithBlock(),
|
||||||
|
}
|
||||||
|
dialOptions = append(dialOptions, opts.DialOptions...)
|
||||||
|
|
||||||
|
conn, err := grpc.DialContext(dialCtx, opts.Endpoint, dialOptions...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, &GatewayError{Op: "dial", Err: err}
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewGalaxyClient(conn, opts), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewGalaxyClient wraps an existing gRPC connection for Galaxy Repository
|
||||||
|
// access. The caller owns closing conn unless it calls Close on the returned
|
||||||
|
// GalaxyClient.
|
||||||
|
func NewGalaxyClient(conn *grpc.ClientConn, opts Options) *GalaxyClient {
|
||||||
|
return &GalaxyClient{
|
||||||
|
conn: conn,
|
||||||
|
raw: pb.NewGalaxyRepositoryClient(conn),
|
||||||
|
opts: opts,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RawClient returns the generated gRPC client for command-specific parity
|
||||||
|
// tests.
|
||||||
|
func (c *GalaxyClient) RawClient() RawGalaxyRepositoryClient {
|
||||||
|
return c.raw
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConnection probes the Galaxy Repository service. It returns the server's
|
||||||
|
// reported ok flag and a non-nil error only when the RPC itself fails.
|
||||||
|
func (c *GalaxyClient) TestConnection(ctx context.Context) (bool, error) {
|
||||||
|
callCtx, cancel := c.callContext(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
reply, err := c.raw.TestConnection(callCtx, &pb.TestConnectionRequest{})
|
||||||
|
if err != nil {
|
||||||
|
return false, &GatewayError{Op: "galaxy test connection", Err: err}
|
||||||
|
}
|
||||||
|
return reply.GetOk(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLastDeployTime returns the Galaxy's last deploy timestamp. When the server
|
||||||
|
// reports present=false (no deploy recorded yet) the call returns
|
||||||
|
// (time.Time{}, false, nil). When present=true the timestamp is returned in
|
||||||
|
// UTC with present=true.
|
||||||
|
func (c *GalaxyClient) GetLastDeployTime(ctx context.Context) (time.Time, bool, error) {
|
||||||
|
callCtx, cancel := c.callContext(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
reply, err := c.raw.GetLastDeployTime(callCtx, &pb.GetLastDeployTimeRequest{})
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, false, &GatewayError{Op: "galaxy get last deploy time", Err: err}
|
||||||
|
}
|
||||||
|
if !reply.GetPresent() {
|
||||||
|
return time.Time{}, false, nil
|
||||||
|
}
|
||||||
|
ts := reply.GetTimeOfLastDeploy()
|
||||||
|
if ts == nil {
|
||||||
|
return time.Time{}, false, nil
|
||||||
|
}
|
||||||
|
return ts.AsTime(), true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DiscoverHierarchy returns the deployed Galaxy object hierarchy with each
|
||||||
|
// object's dynamic attributes. The objects are returned in the order supplied
|
||||||
|
// by the server. The call pages over the server's NextPageToken until the
|
||||||
|
// server signals it has no more results, matching the .NET client.
|
||||||
|
func (c *GalaxyClient) DiscoverHierarchy(ctx context.Context) ([]*GalaxyObject, error) {
|
||||||
|
var objects []*GalaxyObject
|
||||||
|
pageToken := ""
|
||||||
|
seen := map[string]struct{}{}
|
||||||
|
for {
|
||||||
|
callCtx, cancel := c.callContext(ctx)
|
||||||
|
reply, err := c.raw.DiscoverHierarchy(callCtx, &pb.DiscoverHierarchyRequest{
|
||||||
|
PageSize: discoverHierarchyPageSize,
|
||||||
|
PageToken: pageToken,
|
||||||
|
})
|
||||||
|
cancel()
|
||||||
|
if err != nil {
|
||||||
|
return nil, &GatewayError{Op: "galaxy discover hierarchy", Err: err}
|
||||||
|
}
|
||||||
|
objects = append(objects, reply.GetObjects()...)
|
||||||
|
pageToken = reply.GetNextPageToken()
|
||||||
|
if pageToken == "" {
|
||||||
|
return objects, nil
|
||||||
|
}
|
||||||
|
if _, dup := seen[pageToken]; dup {
|
||||||
|
return nil, &GatewayError{
|
||||||
|
Op: "galaxy discover hierarchy",
|
||||||
|
Err: fmt.Errorf("repeated page token %q", pageToken),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
seen[pageToken] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WatchDeployEventsRaw starts the generated WatchDeployEvents stream for callers
|
||||||
|
// that want direct control over Recv. The caller owns the returned stream's
|
||||||
|
// lifetime via ctx cancellation.
|
||||||
|
func (c *GalaxyClient) WatchDeployEventsRaw(ctx context.Context, req *WatchDeployEventsRequest) (RawDeployEventStream, error) {
|
||||||
|
if req == nil {
|
||||||
|
req = &pb.WatchDeployEventsRequest{}
|
||||||
|
}
|
||||||
|
|
||||||
|
stream, err := c.raw.WatchDeployEvents(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, &GatewayError{Op: "galaxy watch deploy events", Err: err}
|
||||||
|
}
|
||||||
|
return stream, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WatchDeployEvents subscribes to Galaxy deploy events. The server emits a
|
||||||
|
// bootstrap event with the current state immediately on subscribe, then one
|
||||||
|
// event per new deploy. When lastSeenDeployTime is non-nil it is forwarded to
|
||||||
|
// the server to suppress the bootstrap event.
|
||||||
|
//
|
||||||
|
// The returned event channel is closed when the server completes the stream
|
||||||
|
// (io.EOF), when ctx is cancelled, or after a terminal error has been
|
||||||
|
// delivered on the error channel. The error channel is also closed once the
|
||||||
|
// stream tears down. Surfaced errors are wrapped in *GatewayError.
|
||||||
|
//
|
||||||
|
// Cancel ctx to tear the stream down cleanly.
|
||||||
|
func (c *GalaxyClient) WatchDeployEvents(
|
||||||
|
ctx context.Context,
|
||||||
|
lastSeenDeployTime *time.Time,
|
||||||
|
) (<-chan *DeployEvent, <-chan error, error) {
|
||||||
|
req := &pb.WatchDeployEventsRequest{}
|
||||||
|
if lastSeenDeployTime != nil {
|
||||||
|
req.LastSeenDeployTime = timestamppb.New(*lastSeenDeployTime)
|
||||||
|
}
|
||||||
|
|
||||||
|
stream, err := c.WatchDeployEventsRaw(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
events := make(chan *DeployEvent, 16)
|
||||||
|
errs := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
defer close(events)
|
||||||
|
defer close(errs)
|
||||||
|
for {
|
||||||
|
event, recvErr := stream.Recv()
|
||||||
|
if recvErr == nil {
|
||||||
|
select {
|
||||||
|
case events <- event:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if recvErr == io.EOF {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if status.Code(recvErr) == codes.Canceled || ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case errs <- &GatewayError{Op: "galaxy watch deploy events", Err: recvErr}:
|
||||||
|
case <-ctx.Done():
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return events, errs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close closes the underlying gRPC connection.
|
||||||
|
func (c *GalaxyClient) Close() error {
|
||||||
|
if c == nil || c.conn == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return c.conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// LazyBrowseNode is one node in a lazy Galaxy hierarchy walk produced by
|
||||||
|
// (*GalaxyClient).Browse. Children are not fetched until Expand is called.
|
||||||
|
// The node is safe for concurrent use; concurrent Expand calls coalesce onto
|
||||||
|
// a single in-flight RPC and do not block snapshot accessors.
|
||||||
|
type LazyBrowseNode struct {
|
||||||
|
client *GalaxyClient
|
||||||
|
object *pb.GalaxyObject
|
||||||
|
hasChildrenHint bool
|
||||||
|
options BrowseChildrenOptions
|
||||||
|
|
||||||
|
// expandLock gates inspection and mutation of expand-coordination state
|
||||||
|
// (expanding, expandDone, expandErr). It is held only briefly; the BrowseChildren
|
||||||
|
// RPC itself runs outside this lock so concurrent readers and waiters are not blocked.
|
||||||
|
expandLock sync.Mutex
|
||||||
|
expanding bool
|
||||||
|
expandDone chan struct{}
|
||||||
|
expandErr error
|
||||||
|
|
||||||
|
// mu protects the children snapshot and isExpanded flag for concurrent
|
||||||
|
// Children() / IsExpanded() readers.
|
||||||
|
mu sync.RWMutex
|
||||||
|
children []*LazyBrowseNode
|
||||||
|
isExpanded bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Object returns the underlying GalaxyObject describing this node.
|
||||||
|
func (n *LazyBrowseNode) Object() *pb.GalaxyObject { return n.object }
|
||||||
|
|
||||||
|
// HasChildrenHint reports the server-supplied hint on whether this node has
|
||||||
|
// matching descendants under the current filter set.
|
||||||
|
func (n *LazyBrowseNode) HasChildrenHint() bool { return n.hasChildrenHint }
|
||||||
|
|
||||||
|
// Children returns a snapshot copy of the currently-loaded child nodes. Returns
|
||||||
|
// an empty slice when Expand has not yet been called.
|
||||||
|
func (n *LazyBrowseNode) Children() []*LazyBrowseNode {
|
||||||
|
n.mu.RLock()
|
||||||
|
defer n.mu.RUnlock()
|
||||||
|
out := make([]*LazyBrowseNode, len(n.children))
|
||||||
|
copy(out, n.children)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsExpanded reports whether Expand has completed successfully on this node.
|
||||||
|
func (n *LazyBrowseNode) IsExpanded() bool {
|
||||||
|
n.mu.RLock()
|
||||||
|
defer n.mu.RUnlock()
|
||||||
|
return n.isExpanded
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expand fetches this node's direct children via BrowseChildren when they have
|
||||||
|
// not yet been loaded. Subsequent calls after a successful Expand are a no-op
|
||||||
|
// and do not issue another RPC.
|
||||||
|
//
|
||||||
|
// Expand is safe to call concurrently from multiple goroutines: callers that
|
||||||
|
// arrive while an expansion is in flight wait on the active RPC and share its
|
||||||
|
// result instead of issuing a second RPC. The RPC itself runs without holding
|
||||||
|
// the snapshot mutex, so concurrent Children() and IsExpanded() callers are
|
||||||
|
// not blocked for the duration of the network round trip.
|
||||||
|
//
|
||||||
|
// Failure semantics: a failed expansion surfaces the same error to every
|
||||||
|
// in-flight waiter, but the node is left in its pre-call state (isExpanded =
|
||||||
|
// false, no in-flight expansion). The next Expand call therefore retries with
|
||||||
|
// a fresh RPC; failures are not sticky.
|
||||||
|
func (n *LazyBrowseNode) Expand(ctx context.Context) error {
|
||||||
|
// Fast path: already expanded.
|
||||||
|
n.mu.RLock()
|
||||||
|
if n.isExpanded {
|
||||||
|
n.mu.RUnlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
n.mu.RUnlock()
|
||||||
|
|
||||||
|
// Either start a new expansion or wait on an existing one.
|
||||||
|
n.expandLock.Lock()
|
||||||
|
n.mu.RLock()
|
||||||
|
alreadyExpanded := n.isExpanded
|
||||||
|
n.mu.RUnlock()
|
||||||
|
if alreadyExpanded {
|
||||||
|
n.expandLock.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if n.expanding {
|
||||||
|
done := n.expandDone
|
||||||
|
n.expandLock.Unlock()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
n.expandLock.Lock()
|
||||||
|
err := n.expandErr
|
||||||
|
n.expandLock.Unlock()
|
||||||
|
return err
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n.expanding = true
|
||||||
|
n.expandDone = make(chan struct{})
|
||||||
|
done := n.expandDone
|
||||||
|
n.expandLock.Unlock()
|
||||||
|
|
||||||
|
// Issue the RPC outside any lock so concurrent readers/waiters are not blocked.
|
||||||
|
parentID := n.object.GetGobjectId()
|
||||||
|
children, err := n.client.browseChildrenInner(ctx, &parentID, n.options)
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
n.mu.Lock()
|
||||||
|
n.children = children
|
||||||
|
n.isExpanded = true
|
||||||
|
n.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish result to waiters and clear the in-flight marker so a failed
|
||||||
|
// expansion can be retried by the next Expand call.
|
||||||
|
n.expandLock.Lock()
|
||||||
|
n.expandErr = err
|
||||||
|
n.expanding = false
|
||||||
|
close(done)
|
||||||
|
n.expandLock.Unlock()
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Browse returns the root nodes of the Galaxy hierarchy. The returned nodes
|
||||||
|
// have only their server-supplied hints populated; call Expand on each node to
|
||||||
|
// fetch its direct children. When opts is nil the server defaults apply.
|
||||||
|
func (c *GalaxyClient) Browse(ctx context.Context, opts *BrowseChildrenOptions) ([]*LazyBrowseNode, error) {
|
||||||
|
effective := BrowseChildrenOptions{}
|
||||||
|
if opts != nil {
|
||||||
|
effective = *opts
|
||||||
|
}
|
||||||
|
return c.browseChildrenInner(ctx, nil, effective)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BrowseChildrenRaw issues a single BrowseChildren RPC and returns the raw
|
||||||
|
// reply for callers that need direct page-token control. Transport-level
|
||||||
|
// failures are wrapped in *GatewayError to match the rest of the client.
|
||||||
|
func (c *GalaxyClient) BrowseChildrenRaw(ctx context.Context, req *pb.BrowseChildrenRequest) (*pb.BrowseChildrenReply, error) {
|
||||||
|
callCtx, cancel := c.callContext(ctx)
|
||||||
|
defer cancel()
|
||||||
|
reply, err := c.raw.BrowseChildren(callCtx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, &GatewayError{Op: "galaxy browse children", Err: err}
|
||||||
|
}
|
||||||
|
return reply, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *GalaxyClient) browseChildrenInner(
|
||||||
|
ctx context.Context,
|
||||||
|
parentGobjectID *int32,
|
||||||
|
opts BrowseChildrenOptions,
|
||||||
|
) ([]*LazyBrowseNode, error) {
|
||||||
|
var nodes []*LazyBrowseNode
|
||||||
|
pageToken := ""
|
||||||
|
seen := map[string]struct{}{}
|
||||||
|
for {
|
||||||
|
req := &pb.BrowseChildrenRequest{
|
||||||
|
PageSize: browseChildrenPageSize,
|
||||||
|
PageToken: pageToken,
|
||||||
|
CategoryIds: opts.CategoryIds,
|
||||||
|
TemplateChainContains: opts.TemplateChainContains,
|
||||||
|
TagNameGlob: opts.TagNameGlob,
|
||||||
|
AlarmBearingOnly: opts.AlarmBearingOnly,
|
||||||
|
HistorizedOnly: opts.HistorizedOnly,
|
||||||
|
}
|
||||||
|
if parentGobjectID != nil {
|
||||||
|
req.Parent = &pb.BrowseChildrenRequest_ParentGobjectId{ParentGobjectId: *parentGobjectID}
|
||||||
|
}
|
||||||
|
if opts.IncludeAttributes != nil {
|
||||||
|
req.IncludeAttributes = opts.IncludeAttributes
|
||||||
|
}
|
||||||
|
|
||||||
|
reply, err := c.BrowseChildrenRaw(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, child := range reply.GetChildren() {
|
||||||
|
hasChildren := reply.GetChildHasChildren()
|
||||||
|
hint := i < len(hasChildren) && hasChildren[i]
|
||||||
|
nodes = append(nodes, &LazyBrowseNode{
|
||||||
|
client: c,
|
||||||
|
object: child,
|
||||||
|
hasChildrenHint: hint,
|
||||||
|
options: opts,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pageToken = reply.GetNextPageToken()
|
||||||
|
if pageToken == "" {
|
||||||
|
return nodes, nil
|
||||||
|
}
|
||||||
|
if _, dup := seen[pageToken]; dup {
|
||||||
|
return nil, &GatewayError{
|
||||||
|
Op: "galaxy browse children",
|
||||||
|
Err: fmt.Errorf("repeated page token %q", pageToken),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
seen[pageToken] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *GalaxyClient) callContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||||
|
timeout := c.opts.CallTimeout
|
||||||
|
if timeout == 0 {
|
||||||
|
timeout = defaultCallTimeout
|
||||||
|
}
|
||||||
|
if timeout < 0 {
|
||||||
|
return ctx, func() {}
|
||||||
|
}
|
||||||
|
if deadline, ok := ctx.Deadline(); ok {
|
||||||
|
timeoutDeadline := time.Now().Add(timeout)
|
||||||
|
if deadline.Before(timeoutDeadline) {
|
||||||
|
return ctx, func() {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return context.WithTimeout(ctx, timeout)
|
||||||
|
}
|
||||||
@@ -0,0 +1,864 @@
|
|||||||
|
package mxgateway
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
|
||||||
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
"google.golang.org/grpc/test/bufconn"
|
||||||
|
"google.golang.org/protobuf/types/known/timestamppb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGalaxyTestConnectionAttachesAuthAndReturnsOk(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
testReply: &pb.TestConnectionReply{Ok: true},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ok, err := client.TestConnection(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("TestConnection() error = %v", err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("TestConnection() ok = false, want true")
|
||||||
|
}
|
||||||
|
if got := fake.testAuth; got != "Bearer test-api-key" {
|
||||||
|
t.Fatalf("authorization metadata = %q, want %q", got, "Bearer test-api-key")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyGetLastDeployTimeReturnsAbsentForPresentFalse(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
deployReply: &pb.GetLastDeployTimeReply{Present: false},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
got, present, err := client.GetLastDeployTime(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetLastDeployTime() error = %v", err)
|
||||||
|
}
|
||||||
|
if present {
|
||||||
|
t.Fatalf("present = true, want false")
|
||||||
|
}
|
||||||
|
if !got.IsZero() {
|
||||||
|
t.Fatalf("time = %v, want zero", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyGetLastDeployTimeReturnsTimestampWhenPresent(t *testing.T) {
|
||||||
|
want := time.Date(2026, 4, 28, 12, 34, 56, 0, time.UTC)
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
deployReply: &pb.GetLastDeployTimeReply{
|
||||||
|
Present: true,
|
||||||
|
TimeOfLastDeploy: timestamppb.New(want),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
got, present, err := client.GetLastDeployTime(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetLastDeployTime() error = %v", err)
|
||||||
|
}
|
||||||
|
if !present {
|
||||||
|
t.Fatalf("present = false, want true")
|
||||||
|
}
|
||||||
|
if !got.Equal(want) {
|
||||||
|
t.Fatalf("time = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyGetLastDeployTimeReturnsAbsentWhenTimestampNil(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
deployReply: &pb.GetLastDeployTimeReply{Present: true, TimeOfLastDeploy: nil},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
got, present, err := client.GetLastDeployTime(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetLastDeployTime() error = %v", err)
|
||||||
|
}
|
||||||
|
if present {
|
||||||
|
t.Fatalf("present = true, want false (nil timestamp)")
|
||||||
|
}
|
||||||
|
if !got.IsZero() {
|
||||||
|
t.Fatalf("time = %v, want zero", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyDiscoverHierarchyReturnsObjects(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
discoverReply: &pb.DiscoverHierarchyReply{
|
||||||
|
Objects: []*pb.GalaxyObject{
|
||||||
|
{
|
||||||
|
GobjectId: 1,
|
||||||
|
TagName: "TestMachine_001",
|
||||||
|
ContainedName: "TestMachine_001",
|
||||||
|
BrowseName: "TestMachine_001",
|
||||||
|
IsArea: false,
|
||||||
|
CategoryId: 7,
|
||||||
|
TemplateChain: []string{"$Object", "$AppObject"},
|
||||||
|
Attributes: []*pb.GalaxyAttribute{
|
||||||
|
{
|
||||||
|
AttributeName: "DownloadPath",
|
||||||
|
FullTagReference: "TestMachine_001.DownloadPath",
|
||||||
|
MxDataType: 8,
|
||||||
|
DataTypeName: "String",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
GobjectId: 2,
|
||||||
|
TagName: "TestMachine_002",
|
||||||
|
ContainedName: "TestMachine_002",
|
||||||
|
ParentGobjectId: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
objects, err := client.DiscoverHierarchy(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("DiscoverHierarchy() error = %v", err)
|
||||||
|
}
|
||||||
|
if len(objects) != 2 {
|
||||||
|
t.Fatalf("len(objects) = %d, want 2", len(objects))
|
||||||
|
}
|
||||||
|
if objects[0].GetTagName() != "TestMachine_001" {
|
||||||
|
t.Fatalf("objects[0].TagName = %q", objects[0].GetTagName())
|
||||||
|
}
|
||||||
|
if len(objects[0].GetAttributes()) != 1 {
|
||||||
|
t.Fatalf("len(attributes) = %d, want 1", len(objects[0].GetAttributes()))
|
||||||
|
}
|
||||||
|
if objects[0].GetAttributes()[0].GetFullTagReference() != "TestMachine_001.DownloadPath" {
|
||||||
|
t.Fatalf("FullTagReference = %q", objects[0].GetAttributes()[0].GetFullTagReference())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyDiscoverHierarchyPaginatesAcrossMultiplePages(t *testing.T) {
|
||||||
|
page1 := &pb.DiscoverHierarchyReply{
|
||||||
|
Objects: []*pb.GalaxyObject{
|
||||||
|
{GobjectId: 1, TagName: "A"},
|
||||||
|
{GobjectId: 2, TagName: "B"},
|
||||||
|
},
|
||||||
|
NextPageToken: "page-2",
|
||||||
|
TotalObjectCount: 3,
|
||||||
|
}
|
||||||
|
page2 := &pb.DiscoverHierarchyReply{
|
||||||
|
Objects: []*pb.GalaxyObject{
|
||||||
|
{GobjectId: 3, TagName: "C"},
|
||||||
|
},
|
||||||
|
TotalObjectCount: 3,
|
||||||
|
}
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
discoverHierarchyReplies: []*pb.DiscoverHierarchyReply{page1, page2},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
objs, err := client.DiscoverHierarchy(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("DiscoverHierarchy: %v", err)
|
||||||
|
}
|
||||||
|
if got, want := len(objs), 3; got != want {
|
||||||
|
t.Fatalf("len(objs) = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
if len(fake.discoverHierarchyCalls) != 2 {
|
||||||
|
t.Fatalf("expected 2 RPC calls, got %d", len(fake.discoverHierarchyCalls))
|
||||||
|
}
|
||||||
|
if fake.discoverHierarchyCalls[0].GetPageSize() != discoverHierarchyPageSize {
|
||||||
|
t.Fatalf("first call PageSize = %d, want %d",
|
||||||
|
fake.discoverHierarchyCalls[0].GetPageSize(), discoverHierarchyPageSize)
|
||||||
|
}
|
||||||
|
if fake.discoverHierarchyCalls[1].GetPageToken() != "page-2" {
|
||||||
|
t.Fatalf("second call page token = %q, want %q",
|
||||||
|
fake.discoverHierarchyCalls[1].GetPageToken(), "page-2")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyDialReturnsGatewayErrorOnRpcFailure(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{failTest: true}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
_, err := client.TestConnection(context.Background())
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("TestConnection() error = nil, want error")
|
||||||
|
}
|
||||||
|
var gwErr *GatewayError
|
||||||
|
if !errors.As(err, &gwErr) {
|
||||||
|
t.Fatalf("error %T does not support errors.As(*GatewayError)", err)
|
||||||
|
}
|
||||||
|
if gwErr.Op != "galaxy test connection" {
|
||||||
|
t.Fatalf("Op = %q, want %q", gwErr.Op, "galaxy test connection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyWatchDeployEventsReceivesEventsInOrder(t *testing.T) {
|
||||||
|
bootstrap := time.Date(2026, 4, 28, 10, 0, 0, 0, time.UTC)
|
||||||
|
deploy1 := time.Date(2026, 4, 28, 10, 5, 0, 0, time.UTC)
|
||||||
|
deploy2 := time.Date(2026, 4, 28, 10, 6, 0, 0, time.UTC)
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
watchEvents: []*pb.DeployEvent{
|
||||||
|
{
|
||||||
|
Sequence: 1,
|
||||||
|
ObservedAt: timestamppb.New(bootstrap),
|
||||||
|
TimeOfLastDeploy: timestamppb.New(deploy1),
|
||||||
|
TimeOfLastDeployPresent: true,
|
||||||
|
ObjectCount: 10,
|
||||||
|
AttributeCount: 42,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Sequence: 2,
|
||||||
|
ObservedAt: timestamppb.New(deploy2),
|
||||||
|
TimeOfLastDeploy: timestamppb.New(deploy2),
|
||||||
|
TimeOfLastDeployPresent: true,
|
||||||
|
ObjectCount: 11,
|
||||||
|
AttributeCount: 44,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
events, errs, err := client.WatchDeployEvents(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("WatchDeployEvents() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got := make([]*DeployEvent, 0, 2)
|
||||||
|
loop:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case ev, ok := <-events:
|
||||||
|
if !ok {
|
||||||
|
break loop
|
||||||
|
}
|
||||||
|
got = append(got, ev)
|
||||||
|
case errVal := <-errs:
|
||||||
|
if errVal != nil {
|
||||||
|
t.Fatalf("error channel: %v", errVal)
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
t.Fatalf("timeout waiting for events; got %d", len(got))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(got) != 2 {
|
||||||
|
t.Fatalf("len(events) = %d, want 2", len(got))
|
||||||
|
}
|
||||||
|
if got[0].GetSequence() != 1 || got[1].GetSequence() != 2 {
|
||||||
|
t.Fatalf("sequences = [%d,%d], want [1,2]", got[0].GetSequence(), got[1].GetSequence())
|
||||||
|
}
|
||||||
|
if !got[0].GetTimeOfLastDeployPresent() {
|
||||||
|
t.Fatalf("event[0] TimeOfLastDeployPresent = false, want true")
|
||||||
|
}
|
||||||
|
if got[0].GetObjectCount() != 10 || got[0].GetAttributeCount() != 42 {
|
||||||
|
t.Fatalf("event[0] counts = (%d,%d), want (10,42)", got[0].GetObjectCount(), got[0].GetAttributeCount())
|
||||||
|
}
|
||||||
|
if !got[0].GetTimeOfLastDeploy().AsTime().Equal(deploy1) {
|
||||||
|
t.Fatalf("event[0] TimeOfLastDeploy = %v, want %v", got[0].GetTimeOfLastDeploy().AsTime(), deploy1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyWatchDeployEventsForwardsLastSeenDeployTime(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
watchEvents: []*pb.DeployEvent{
|
||||||
|
{Sequence: 7},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
lastSeen := time.Date(2026, 4, 28, 9, 0, 0, 0, time.UTC)
|
||||||
|
events, errs, err := client.WatchDeployEvents(ctx, &lastSeen)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("WatchDeployEvents() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drain everything.
|
||||||
|
loop:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case _, ok := <-events:
|
||||||
|
if !ok {
|
||||||
|
break loop
|
||||||
|
}
|
||||||
|
case errVal := <-errs:
|
||||||
|
if errVal != nil {
|
||||||
|
t.Fatalf("error channel: %v", errVal)
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
t.Fatalf("timeout draining events")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if fake.watchRequest == nil {
|
||||||
|
t.Fatalf("server did not receive a request")
|
||||||
|
}
|
||||||
|
gotTs := fake.watchRequest.GetLastSeenDeployTime()
|
||||||
|
if gotTs == nil {
|
||||||
|
t.Fatalf("LastSeenDeployTime = nil, want %v", lastSeen)
|
||||||
|
}
|
||||||
|
if !gotTs.AsTime().Equal(lastSeen) {
|
||||||
|
t.Fatalf("LastSeenDeployTime = %v, want %v", gotTs.AsTime(), lastSeen)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyWatchDeployEventsCancelTearsDownStream(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
watchEvents: []*pb.DeployEvent{
|
||||||
|
{Sequence: 1},
|
||||||
|
},
|
||||||
|
watchHoldOpen: true,
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
streamCtx, cancelStream := context.WithCancel(context.Background())
|
||||||
|
|
||||||
|
events, errs, err := client.WatchDeployEvents(streamCtx, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("WatchDeployEvents() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for the bootstrap event to arrive.
|
||||||
|
select {
|
||||||
|
case ev, ok := <-events:
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("events channel closed before delivering bootstrap")
|
||||||
|
}
|
||||||
|
if ev.GetSequence() != 1 {
|
||||||
|
t.Fatalf("got seq=%d, want 1", ev.GetSequence())
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatalf("timeout waiting for bootstrap event")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cancel the stream; both channels must close cleanly without delivering an error.
|
||||||
|
cancelStream()
|
||||||
|
|
||||||
|
deadline := time.After(2 * time.Second)
|
||||||
|
for events != nil || errs != nil {
|
||||||
|
select {
|
||||||
|
case _, ok := <-events:
|
||||||
|
if !ok {
|
||||||
|
events = nil
|
||||||
|
}
|
||||||
|
case errVal, ok := <-errs:
|
||||||
|
if !ok {
|
||||||
|
errs = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if errVal != nil {
|
||||||
|
t.Fatalf("error after cancel: %v", errVal)
|
||||||
|
}
|
||||||
|
case <-deadline:
|
||||||
|
t.Fatalf("channels did not close after cancel; events nil=%v errs nil=%v", events == nil, errs == nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newGalaxyBufconnClient(t *testing.T, fake *fakeGalaxyServer) (*GalaxyClient, func()) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
listener := bufconn.Listen(bufSize)
|
||||||
|
server := grpc.NewServer()
|
||||||
|
pb.RegisterGalaxyRepositoryServer(server, fake)
|
||||||
|
go func() {
|
||||||
|
if err := server.Serve(listener); err != nil && !errors.Is(err, grpc.ErrServerStopped) {
|
||||||
|
t.Errorf("bufconn server failed: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
dialer := func(ctx context.Context, _ string) (net.Conn, error) {
|
||||||
|
return listener.DialContext(ctx)
|
||||||
|
}
|
||||||
|
client, err := DialGalaxy(context.Background(), Options{
|
||||||
|
Endpoint: "bufnet",
|
||||||
|
APIKey: "test-api-key",
|
||||||
|
Plaintext: true,
|
||||||
|
DialOptions: []grpc.DialOption{
|
||||||
|
grpc.WithContextDialer(dialer),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("DialGalaxy() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return client, func() {
|
||||||
|
client.Close()
|
||||||
|
server.Stop()
|
||||||
|
listener.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeGalaxyServer struct {
|
||||||
|
pb.UnimplementedGalaxyRepositoryServer
|
||||||
|
|
||||||
|
testReply *pb.TestConnectionReply
|
||||||
|
testAuth string
|
||||||
|
failTest bool
|
||||||
|
deployReply *pb.GetLastDeployTimeReply
|
||||||
|
discoverReply *pb.DiscoverHierarchyReply
|
||||||
|
discoverHierarchyCalls []*pb.DiscoverHierarchyRequest
|
||||||
|
discoverHierarchyReplies []*pb.DiscoverHierarchyReply
|
||||||
|
watchEvents []*pb.DeployEvent
|
||||||
|
watchRequest *pb.WatchDeployEventsRequest
|
||||||
|
watchSendInterval time.Duration
|
||||||
|
watchHoldOpen bool
|
||||||
|
browseChildrenCalls []*pb.BrowseChildrenRequest
|
||||||
|
browseChildrenReplies []*pb.BrowseChildrenReply
|
||||||
|
browseChildrenError error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeGalaxyServer) TestConnection(ctx context.Context, req *pb.TestConnectionRequest) (*pb.TestConnectionReply, error) {
|
||||||
|
s.testAuth = authorizationFromContext(ctx)
|
||||||
|
if s.failTest {
|
||||||
|
return nil, errors.New("simulated failure")
|
||||||
|
}
|
||||||
|
if s.testReply != nil {
|
||||||
|
return s.testReply, nil
|
||||||
|
}
|
||||||
|
return &pb.TestConnectionReply{Ok: true}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeGalaxyServer) GetLastDeployTime(ctx context.Context, req *pb.GetLastDeployTimeRequest) (*pb.GetLastDeployTimeReply, error) {
|
||||||
|
if s.deployReply != nil {
|
||||||
|
return s.deployReply, nil
|
||||||
|
}
|
||||||
|
return &pb.GetLastDeployTimeReply{Present: false}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeGalaxyServer) DiscoverHierarchy(ctx context.Context, req *pb.DiscoverHierarchyRequest) (*pb.DiscoverHierarchyReply, error) {
|
||||||
|
s.discoverHierarchyCalls = append(s.discoverHierarchyCalls, req)
|
||||||
|
if len(s.discoverHierarchyReplies) > 0 {
|
||||||
|
reply := s.discoverHierarchyReplies[0]
|
||||||
|
s.discoverHierarchyReplies = s.discoverHierarchyReplies[1:]
|
||||||
|
return reply, nil
|
||||||
|
}
|
||||||
|
if s.discoverReply != nil {
|
||||||
|
return s.discoverReply, nil
|
||||||
|
}
|
||||||
|
return &pb.DiscoverHierarchyReply{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeGalaxyServer) WatchDeployEvents(req *pb.WatchDeployEventsRequest, stream grpc.ServerStreamingServer[pb.DeployEvent]) error {
|
||||||
|
s.watchRequest = req
|
||||||
|
for _, event := range s.watchEvents {
|
||||||
|
if err := stream.Send(event); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if s.watchSendInterval > 0 {
|
||||||
|
select {
|
||||||
|
case <-time.After(s.watchSendInterval):
|
||||||
|
case <-stream.Context().Done():
|
||||||
|
return stream.Context().Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.watchHoldOpen {
|
||||||
|
<-stream.Context().Done()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeGalaxyServer) BrowseChildren(ctx context.Context, req *pb.BrowseChildrenRequest) (*pb.BrowseChildrenReply, error) {
|
||||||
|
s.browseChildrenCalls = append(s.browseChildrenCalls, req)
|
||||||
|
if s.browseChildrenError != nil {
|
||||||
|
err := s.browseChildrenError
|
||||||
|
s.browseChildrenError = nil
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(s.browseChildrenReplies) == 0 {
|
||||||
|
return &pb.BrowseChildrenReply{}, nil
|
||||||
|
}
|
||||||
|
reply := s.browseChildrenReplies[0]
|
||||||
|
s.browseChildrenReplies = s.browseChildrenReplies[1:]
|
||||||
|
return reply, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func obj(id int32, tag string, isArea bool) *pb.GalaxyObject {
|
||||||
|
return &pb.GalaxyObject{
|
||||||
|
GobjectId: id,
|
||||||
|
TagName: tag,
|
||||||
|
BrowseName: tag,
|
||||||
|
IsArea: isArea,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildBrowseReply(children []*pb.GalaxyObject, hasChildren []bool, seq uint64) *pb.BrowseChildrenReply {
|
||||||
|
return &pb.BrowseChildrenReply{
|
||||||
|
TotalChildCount: int32(len(children)),
|
||||||
|
CacheSequence: seq,
|
||||||
|
Children: children,
|
||||||
|
ChildHasChildren: hasChildren,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyBrowseNoParentReturnsRoots(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
browseChildrenReplies: []*pb.BrowseChildrenReply{
|
||||||
|
buildBrowseReply(
|
||||||
|
[]*pb.GalaxyObject{obj(1, "Plant", true), obj(99, "Other", false)},
|
||||||
|
[]bool{true, false},
|
||||||
|
7,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
roots, err := client.Browse(context.Background(), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Browse: %v", err)
|
||||||
|
}
|
||||||
|
if got, want := len(roots), 2; got != want {
|
||||||
|
t.Fatalf("len(roots) = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
if roots[0].Object().GetTagName() != "Plant" {
|
||||||
|
t.Fatalf("roots[0].TagName = %q", roots[0].Object().GetTagName())
|
||||||
|
}
|
||||||
|
if !roots[0].HasChildrenHint() {
|
||||||
|
t.Fatal("roots[0].HasChildrenHint = false, want true")
|
||||||
|
}
|
||||||
|
if roots[0].IsExpanded() {
|
||||||
|
t.Fatal("roots[0].IsExpanded = true, want false")
|
||||||
|
}
|
||||||
|
if roots[1].HasChildrenHint() {
|
||||||
|
t.Fatal("roots[1].HasChildrenHint = true, want false")
|
||||||
|
}
|
||||||
|
if len(fake.browseChildrenCalls) != 1 {
|
||||||
|
t.Fatalf("BrowseChildren calls = %d, want 1", len(fake.browseChildrenCalls))
|
||||||
|
}
|
||||||
|
if fake.browseChildrenCalls[0].GetParent() != nil {
|
||||||
|
t.Fatalf("root browse should not set Parent oneof, got %T", fake.browseChildrenCalls[0].GetParent())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyBrowseExpandPopulatesChildrenAndMarksExpanded(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
browseChildrenReplies: []*pb.BrowseChildrenReply{
|
||||||
|
buildBrowseReply(
|
||||||
|
[]*pb.GalaxyObject{obj(1, "Plant", true)},
|
||||||
|
[]bool{true},
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
buildBrowseReply(
|
||||||
|
[]*pb.GalaxyObject{obj(10, "Area1", true), obj(11, "Tank1", false)},
|
||||||
|
[]bool{true, false},
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
roots, err := client.Browse(context.Background(), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Browse: %v", err)
|
||||||
|
}
|
||||||
|
if len(roots) != 1 {
|
||||||
|
t.Fatalf("len(roots) = %d, want 1", len(roots))
|
||||||
|
}
|
||||||
|
plant := roots[0]
|
||||||
|
if plant.IsExpanded() {
|
||||||
|
t.Fatal("plant.IsExpanded = true before Expand, want false")
|
||||||
|
}
|
||||||
|
if err := plant.Expand(context.Background()); err != nil {
|
||||||
|
t.Fatalf("Expand: %v", err)
|
||||||
|
}
|
||||||
|
if !plant.IsExpanded() {
|
||||||
|
t.Fatal("plant.IsExpanded = false after Expand, want true")
|
||||||
|
}
|
||||||
|
children := plant.Children()
|
||||||
|
if len(children) != 2 {
|
||||||
|
t.Fatalf("len(children) = %d, want 2", len(children))
|
||||||
|
}
|
||||||
|
if children[0].Object().GetTagName() != "Area1" {
|
||||||
|
t.Fatalf("children[0].TagName = %q, want Area1", children[0].Object().GetTagName())
|
||||||
|
}
|
||||||
|
if !children[0].HasChildrenHint() {
|
||||||
|
t.Fatal("children[0].HasChildrenHint = false, want true")
|
||||||
|
}
|
||||||
|
if children[1].HasChildrenHint() {
|
||||||
|
t.Fatal("children[1].HasChildrenHint = true, want false")
|
||||||
|
}
|
||||||
|
if len(fake.browseChildrenCalls) != 2 {
|
||||||
|
t.Fatalf("BrowseChildren calls = %d, want 2", len(fake.browseChildrenCalls))
|
||||||
|
}
|
||||||
|
parent := fake.browseChildrenCalls[1].GetParent()
|
||||||
|
parentGobj, ok := parent.(*pb.BrowseChildrenRequest_ParentGobjectId)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("Parent oneof = %T, want *BrowseChildrenRequest_ParentGobjectId", parent)
|
||||||
|
}
|
||||||
|
if parentGobj.ParentGobjectId != 1 {
|
||||||
|
t.Fatalf("ParentGobjectId = %d, want 1", parentGobj.ParentGobjectId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyBrowseExpandIdempotentNoSecondRpc(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
browseChildrenReplies: []*pb.BrowseChildrenReply{
|
||||||
|
buildBrowseReply(
|
||||||
|
[]*pb.GalaxyObject{obj(1, "Plant", true)},
|
||||||
|
[]bool{true},
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
buildBrowseReply(
|
||||||
|
[]*pb.GalaxyObject{obj(10, "Area1", true)},
|
||||||
|
[]bool{false},
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
roots, err := client.Browse(context.Background(), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Browse: %v", err)
|
||||||
|
}
|
||||||
|
plant := roots[0]
|
||||||
|
if err := plant.Expand(context.Background()); err != nil {
|
||||||
|
t.Fatalf("Expand #1: %v", err)
|
||||||
|
}
|
||||||
|
callsAfterFirst := len(fake.browseChildrenCalls)
|
||||||
|
if callsAfterFirst != 2 {
|
||||||
|
t.Fatalf("BrowseChildren calls after first Expand = %d, want 2", callsAfterFirst)
|
||||||
|
}
|
||||||
|
if err := plant.Expand(context.Background()); err != nil {
|
||||||
|
t.Fatalf("Expand #2: %v", err)
|
||||||
|
}
|
||||||
|
if got := len(fake.browseChildrenCalls); got != callsAfterFirst {
|
||||||
|
t.Fatalf("BrowseChildren calls after second Expand = %d, want %d (no extra RPC)", got, callsAfterFirst)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyBrowseExpandUnknownParentReturnsNotFoundError(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
browseChildrenReplies: []*pb.BrowseChildrenReply{
|
||||||
|
buildBrowseReply(
|
||||||
|
[]*pb.GalaxyObject{obj(1, "Plant", true)},
|
||||||
|
[]bool{true},
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
browseChildrenError: status.Error(codes.NotFound, "parent not found"),
|
||||||
|
}
|
||||||
|
// The first Browse() consumes the first reply; the next call (Expand) will
|
||||||
|
// then hit browseChildrenError. We need the error to fire only on the second
|
||||||
|
// call, so seed the reply first and let the call sequence consume them in
|
||||||
|
// order. Because BrowseChildren in the fake consumes browseChildrenError
|
||||||
|
// before falling through to replies, swap the strategy: keep the root reply
|
||||||
|
// but have BrowseChildren return the error on the second call. We do this by
|
||||||
|
// emptying the reply list after the first Browse.
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
// First call returns the error (because browseChildrenError takes precedence).
|
||||||
|
// To avoid that, clear it for the root call by performing a manual setup: we
|
||||||
|
// pre-stage replies first, then set the error after the first call. Easiest:
|
||||||
|
// pre-Browse() with error=nil, then set error before Expand.
|
||||||
|
fake.browseChildrenError = nil
|
||||||
|
roots, err := client.Browse(context.Background(), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Browse: %v", err)
|
||||||
|
}
|
||||||
|
if len(roots) != 1 {
|
||||||
|
t.Fatalf("len(roots) = %d, want 1", len(roots))
|
||||||
|
}
|
||||||
|
fake.browseChildrenError = status.Error(codes.NotFound, "parent not found")
|
||||||
|
|
||||||
|
err = roots[0].Expand(context.Background())
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Expand: error = nil, want NotFound")
|
||||||
|
}
|
||||||
|
if status.Code(err) != codes.NotFound {
|
||||||
|
t.Fatalf("status.Code = %s, want NotFound", status.Code(err))
|
||||||
|
}
|
||||||
|
if roots[0].IsExpanded() {
|
||||||
|
t.Fatal("roots[0].IsExpanded = true after failed Expand, want false")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyBrowseExpandMultiPageGathersAllPages(t *testing.T) {
|
||||||
|
firstPage := buildBrowseReply(
|
||||||
|
[]*pb.GalaxyObject{obj(1, "Plant", true)},
|
||||||
|
[]bool{true},
|
||||||
|
7,
|
||||||
|
)
|
||||||
|
|
||||||
|
pageA := buildBrowseReply(
|
||||||
|
[]*pb.GalaxyObject{obj(10, "Child1", false), obj(11, "Child2", false)},
|
||||||
|
[]bool{false, false},
|
||||||
|
7,
|
||||||
|
)
|
||||||
|
pageA.NextPageToken = "7:abc:2"
|
||||||
|
pageB := buildBrowseReply(
|
||||||
|
[]*pb.GalaxyObject{obj(12, "Child3", false)},
|
||||||
|
[]bool{false},
|
||||||
|
7,
|
||||||
|
)
|
||||||
|
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
browseChildrenReplies: []*pb.BrowseChildrenReply{firstPage, pageA, pageB},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
roots, err := client.Browse(context.Background(), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Browse: %v", err)
|
||||||
|
}
|
||||||
|
if err := roots[0].Expand(context.Background()); err != nil {
|
||||||
|
t.Fatalf("Expand: %v", err)
|
||||||
|
}
|
||||||
|
children := roots[0].Children()
|
||||||
|
if len(children) != 3 {
|
||||||
|
t.Fatalf("len(children) = %d, want 3", len(children))
|
||||||
|
}
|
||||||
|
if len(fake.browseChildrenCalls) != 3 {
|
||||||
|
t.Fatalf("BrowseChildren calls = %d, want 3", len(fake.browseChildrenCalls))
|
||||||
|
}
|
||||||
|
if got := fake.browseChildrenCalls[2].GetPageToken(); got != "7:abc:2" {
|
||||||
|
t.Fatalf("third call PageToken = %q, want %q", got, "7:abc:2")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyBrowseWithFilterForwardsToRequest(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
browseChildrenReplies: []*pb.BrowseChildrenReply{
|
||||||
|
buildBrowseReply(nil, nil, 1),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
include := true
|
||||||
|
opts := &BrowseChildrenOptions{
|
||||||
|
CategoryIds: []int32{7, 9},
|
||||||
|
TemplateChainContains: []string{"$AppObject"},
|
||||||
|
TagNameGlob: "Tank*",
|
||||||
|
IncludeAttributes: &include,
|
||||||
|
AlarmBearingOnly: true,
|
||||||
|
HistorizedOnly: true,
|
||||||
|
}
|
||||||
|
if _, err := client.Browse(context.Background(), opts); err != nil {
|
||||||
|
t.Fatalf("Browse: %v", err)
|
||||||
|
}
|
||||||
|
if len(fake.browseChildrenCalls) != 1 {
|
||||||
|
t.Fatalf("BrowseChildren calls = %d, want 1", len(fake.browseChildrenCalls))
|
||||||
|
}
|
||||||
|
got := fake.browseChildrenCalls[0]
|
||||||
|
if want := []int32{7, 9}; len(got.GetCategoryIds()) != 2 || got.GetCategoryIds()[0] != want[0] || got.GetCategoryIds()[1] != want[1] {
|
||||||
|
t.Fatalf("CategoryIds = %v, want %v", got.GetCategoryIds(), want)
|
||||||
|
}
|
||||||
|
if want := []string{"$AppObject"}; len(got.GetTemplateChainContains()) != 1 || got.GetTemplateChainContains()[0] != want[0] {
|
||||||
|
t.Fatalf("TemplateChainContains = %v, want %v", got.GetTemplateChainContains(), want)
|
||||||
|
}
|
||||||
|
if got.GetTagNameGlob() != "Tank*" {
|
||||||
|
t.Fatalf("TagNameGlob = %q, want %q", got.GetTagNameGlob(), "Tank*")
|
||||||
|
}
|
||||||
|
if !got.GetIncludeAttributes() {
|
||||||
|
t.Fatal("IncludeAttributes = false, want true")
|
||||||
|
}
|
||||||
|
if !got.GetAlarmBearingOnly() {
|
||||||
|
t.Fatal("AlarmBearingOnly = false, want true")
|
||||||
|
}
|
||||||
|
if !got.GetHistorizedOnly() {
|
||||||
|
t.Fatal("HistorizedOnly = false, want true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyBrowseExpandConcurrentCallersOnlyFireOneRpc(t *testing.T) {
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
browseChildrenReplies: []*pb.BrowseChildrenReply{
|
||||||
|
// roots
|
||||||
|
buildBrowseReply([]*pb.GalaxyObject{obj(1, "Plant", true)}, []bool{true}, 7),
|
||||||
|
// one expand: one child
|
||||||
|
buildBrowseReply([]*pb.GalaxyObject{obj(2, "Mixer", false)}, []bool{false}, 7),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
roots, err := client.Browse(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Browse: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errs := make(chan error, 10)
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
errs <- roots[0].Expand(ctx)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
close(errs)
|
||||||
|
for err := range errs {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("concurrent Expand: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !roots[0].IsExpanded() {
|
||||||
|
t.Fatal("IsExpanded() = false after 10 concurrent expands")
|
||||||
|
}
|
||||||
|
if got, want := len(roots[0].Children()), 1; got != want {
|
||||||
|
t.Fatalf("len(children) = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
// 1 roots fetch + exactly 1 expand fetch.
|
||||||
|
if got, want := len(fake.browseChildrenCalls), 2; got != want {
|
||||||
|
t.Fatalf("RPC count = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGalaxyBrowseChildrenRejectsRepeatedPageToken(t *testing.T) {
|
||||||
|
// Build a reply that carries a non-empty NextPageToken so browseChildrenInner
|
||||||
|
// will request a second page. Queue the same reply twice so the second response
|
||||||
|
// returns the same page token, triggering the duplicate-token guard.
|
||||||
|
page := buildBrowseReply(
|
||||||
|
[]*pb.GalaxyObject{obj(1, "Plant", true)},
|
||||||
|
[]bool{true},
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
page.NextPageToken = "1:abc:1"
|
||||||
|
|
||||||
|
fake := &fakeGalaxyServer{
|
||||||
|
browseChildrenReplies: []*pb.BrowseChildrenReply{page, page},
|
||||||
|
}
|
||||||
|
client, cleanup := newGalaxyBufconnClient(t, fake)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
_, err := client.Browse(context.Background(), nil)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Browse: error = nil, want repeated-page-token error")
|
||||||
|
}
|
||||||
|
var gwErr *GatewayError
|
||||||
|
if !errors.As(err, &gwErr) {
|
||||||
|
t.Fatalf("error type = %T, want *GatewayError; err = %v", err, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,16 +11,51 @@ import (
|
|||||||
|
|
||||||
// Options configures gateway connections.
|
// Options configures gateway connections.
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Endpoint string
|
// Endpoint is the gateway host:port address to dial.
|
||||||
APIKey string
|
Endpoint string
|
||||||
Plaintext bool
|
// APIKey is the bearer token attached to outgoing gRPC metadata.
|
||||||
CACertFile string
|
APIKey string
|
||||||
ServerNameOverride string
|
// Plaintext disables TLS and uses insecure credentials when true.
|
||||||
DialTimeout time.Duration
|
Plaintext bool
|
||||||
CallTimeout time.Duration
|
// CACertFile points to a PEM file used to verify the gateway certificate.
|
||||||
TLSConfig *tls.Config
|
CACertFile string
|
||||||
|
// ServerNameOverride overrides the TLS SNI/SAN name presented to the gateway.
|
||||||
|
ServerNameOverride string
|
||||||
|
// DialTimeout bounds the blocking Dial; zero applies a built-in default.
|
||||||
|
DialTimeout time.Duration
|
||||||
|
// CallTimeout bounds each unary RPC; zero applies a built-in default and
|
||||||
|
// negative disables the bound entirely.
|
||||||
|
CallTimeout time.Duration
|
||||||
|
// TLSConfig supplies a custom TLS configuration; takes precedence over
|
||||||
|
// CACertFile when TransportCredentials is unset.
|
||||||
|
TLSConfig *tls.Config
|
||||||
|
// TransportCredentials, when non-nil, overrides every other transport-level
|
||||||
|
// option and is used as-is.
|
||||||
TransportCredentials credentials.TransportCredentials
|
TransportCredentials credentials.TransportCredentials
|
||||||
DialOptions []grpc.DialOption
|
// DialOptions are appended to the gRPC dial options after the defaults.
|
||||||
|
DialOptions []grpc.DialOption
|
||||||
|
}
|
||||||
|
|
||||||
|
// BrowseChildrenOptions configures lazy Galaxy hierarchy walks performed by
|
||||||
|
// (*GalaxyClient).Browse and (*LazyBrowseNode).Expand. All fields are optional;
|
||||||
|
// the zero value matches the dashboard default (no filters, all attributes per
|
||||||
|
// the server default).
|
||||||
|
type BrowseChildrenOptions struct {
|
||||||
|
// CategoryIds restricts results to the listed Galaxy category ids when set.
|
||||||
|
CategoryIds []int32
|
||||||
|
// TemplateChainContains restricts results to objects whose template chain
|
||||||
|
// contains any of the listed template tag names.
|
||||||
|
TemplateChainContains []string
|
||||||
|
// TagNameGlob restricts results to objects whose tag name matches the glob
|
||||||
|
// pattern when non-empty.
|
||||||
|
TagNameGlob string
|
||||||
|
// IncludeAttributes overrides the server default for attribute inclusion when
|
||||||
|
// non-nil. The pointer form mirrors the proto's optional field.
|
||||||
|
IncludeAttributes *bool
|
||||||
|
// AlarmBearingOnly limits results to alarm-bearing objects when true.
|
||||||
|
AlarmBearingOnly bool
|
||||||
|
// HistorizedOnly limits results to historized objects when true.
|
||||||
|
HistorizedOnly bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// RedactedAPIKey returns a display-safe representation of the configured API
|
// RedactedAPIKey returns a display-safe representation of the configured API
|
||||||
|
|||||||
@@ -5,18 +5,48 @@ import (
|
|||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
|
pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
|
||||||
"google.golang.org/grpc/codes"
|
"google.golang.org/grpc/codes"
|
||||||
"google.golang.org/grpc/status"
|
"google.golang.org/grpc/status"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const maxBulkItems = 1000
|
||||||
|
|
||||||
// EventResult carries either the next ordered event or a terminal stream error.
|
// EventResult carries either the next ordered event or a terminal stream error.
|
||||||
type EventResult struct {
|
type EventResult struct {
|
||||||
|
// Event is the next event from the stream when Err is nil.
|
||||||
Event *MxEvent
|
Event *MxEvent
|
||||||
Err error
|
// Err is the terminal stream error; when non-nil no further results follow.
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// EventSubscription owns a running gateway event stream.
|
||||||
|
type EventSubscription struct {
|
||||||
|
results <-chan EventResult
|
||||||
|
cancel context.CancelFunc
|
||||||
|
done <-chan struct{}
|
||||||
|
once sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
// Events returns the stream results channel.
|
||||||
|
func (s *EventSubscription) Events() <-chan EventResult {
|
||||||
|
return s.results
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close cancels the stream and waits for the receive goroutine to stop.
|
||||||
|
func (s *EventSubscription) Close() {
|
||||||
|
if s == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.once.Do(func() {
|
||||||
|
s.cancel()
|
||||||
|
<-s.done
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Session represents one gateway-backed MXAccess session.
|
// Session represents one gateway-backed MXAccess session.
|
||||||
@@ -104,6 +134,25 @@ func (s *Session) Unregister(ctx context.Context, serverHandle int32) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RemoveItem invokes MXAccess RemoveItem.
|
||||||
|
func (s *Session) RemoveItem(ctx context.Context, serverHandle, itemHandle int32) error {
|
||||||
|
_, err := s.RemoveItemRaw(ctx, serverHandle, itemHandle)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveItemRaw invokes MXAccess RemoveItem and returns the raw reply.
|
||||||
|
func (s *Session) RemoveItemRaw(ctx context.Context, serverHandle, itemHandle int32) (*MxCommandReply, error) {
|
||||||
|
return s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_REMOVE_ITEM,
|
||||||
|
Payload: &pb.MxCommand_RemoveItem{
|
||||||
|
RemoveItem: &pb.RemoveItemCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
ItemHandle: itemHandle,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// AddItem invokes MXAccess AddItem and returns the item handle.
|
// AddItem invokes MXAccess AddItem and returns the item handle.
|
||||||
func (s *Session) AddItem(ctx context.Context, serverHandle int32, itemDefinition string) (int32, error) {
|
func (s *Session) AddItem(ctx context.Context, serverHandle int32, itemDefinition string) (int32, error) {
|
||||||
reply, err := s.AddItemRaw(ctx, serverHandle, itemDefinition)
|
reply, err := s.AddItemRaw(ctx, serverHandle, itemDefinition)
|
||||||
@@ -182,6 +231,330 @@ func (s *Session) AdviseRaw(ctx context.Context, serverHandle, itemHandle int32)
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UnAdvise invokes MXAccess UnAdvise.
|
||||||
|
func (s *Session) UnAdvise(ctx context.Context, serverHandle, itemHandle int32) error {
|
||||||
|
_, err := s.UnAdviseRaw(ctx, serverHandle, itemHandle)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnAdviseRaw invokes MXAccess UnAdvise and returns the raw reply.
|
||||||
|
func (s *Session) UnAdviseRaw(ctx context.Context, serverHandle, itemHandle int32) (*MxCommandReply, error) {
|
||||||
|
return s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_UN_ADVISE,
|
||||||
|
Payload: &pb.MxCommand_UnAdvise{
|
||||||
|
UnAdvise: &pb.UnAdviseCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
ItemHandle: itemHandle,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddItemBulk invokes MXAccess AddItem for each tag inside one gateway command.
|
||||||
|
func (s *Session) AddItemBulk(ctx context.Context, serverHandle int32, tagAddresses []string) ([]*SubscribeResult, error) {
|
||||||
|
if tagAddresses == nil {
|
||||||
|
return nil, errors.New("mxgateway: tag addresses are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("tag addresses", len(tagAddresses)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_ADD_ITEM_BULK,
|
||||||
|
Payload: &pb.MxCommand_AddItemBulk{
|
||||||
|
AddItemBulk: &pb.AddItemBulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
TagAddresses: tagAddresses,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetAddItemBulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdviseItemBulk invokes MXAccess Advise for each item handle inside one gateway command.
|
||||||
|
func (s *Session) AdviseItemBulk(ctx context.Context, serverHandle int32, itemHandles []int32) ([]*SubscribeResult, error) {
|
||||||
|
if itemHandles == nil {
|
||||||
|
return nil, errors.New("mxgateway: item handles are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("item handles", len(itemHandles)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_ADVISE_ITEM_BULK,
|
||||||
|
Payload: &pb.MxCommand_AdviseItemBulk{
|
||||||
|
AdviseItemBulk: &pb.AdviseItemBulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
ItemHandles: itemHandles,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetAdviseItemBulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveItemBulk invokes MXAccess RemoveItem for each item handle inside one gateway command.
|
||||||
|
func (s *Session) RemoveItemBulk(ctx context.Context, serverHandle int32, itemHandles []int32) ([]*SubscribeResult, error) {
|
||||||
|
if itemHandles == nil {
|
||||||
|
return nil, errors.New("mxgateway: item handles are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("item handles", len(itemHandles)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_REMOVE_ITEM_BULK,
|
||||||
|
Payload: &pb.MxCommand_RemoveItemBulk{
|
||||||
|
RemoveItemBulk: &pb.RemoveItemBulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
ItemHandles: itemHandles,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetRemoveItemBulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnAdviseItemBulk invokes MXAccess UnAdvise for each item handle inside one gateway command.
|
||||||
|
func (s *Session) UnAdviseItemBulk(ctx context.Context, serverHandle int32, itemHandles []int32) ([]*SubscribeResult, error) {
|
||||||
|
if itemHandles == nil {
|
||||||
|
return nil, errors.New("mxgateway: item handles are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("item handles", len(itemHandles)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_UN_ADVISE_ITEM_BULK,
|
||||||
|
Payload: &pb.MxCommand_UnAdviseItemBulk{
|
||||||
|
UnAdviseItemBulk: &pb.UnAdviseItemBulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
ItemHandles: itemHandles,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetUnAdviseItemBulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubscribeBulk invokes AddItem and Advise for each tag inside one gateway command.
|
||||||
|
func (s *Session) SubscribeBulk(ctx context.Context, serverHandle int32, tagAddresses []string) ([]*SubscribeResult, error) {
|
||||||
|
if tagAddresses == nil {
|
||||||
|
return nil, errors.New("mxgateway: tag addresses are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("tag addresses", len(tagAddresses)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_SUBSCRIBE_BULK,
|
||||||
|
Payload: &pb.MxCommand_SubscribeBulk{
|
||||||
|
SubscribeBulk: &pb.SubscribeBulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
TagAddresses: tagAddresses,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetSubscribeBulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnsubscribeBulk invokes UnAdvise and RemoveItem for each item handle inside one gateway command.
|
||||||
|
func (s *Session) UnsubscribeBulk(ctx context.Context, serverHandle int32, itemHandles []int32) ([]*SubscribeResult, error) {
|
||||||
|
if itemHandles == nil {
|
||||||
|
return nil, errors.New("mxgateway: item handles are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("item handles", len(itemHandles)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_UNSUBSCRIBE_BULK,
|
||||||
|
Payload: &pb.MxCommand_UnsubscribeBulk{
|
||||||
|
UnsubscribeBulk: &pb.UnsubscribeBulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
ItemHandles: itemHandles,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetUnsubscribeBulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteBulk invokes MXAccess Write sequentially for each entry inside one gateway command.
|
||||||
|
// Per-entry failures appear as BulkWriteResult entries with WasSuccessful=false; the call
|
||||||
|
// never returns an error for per-entry MXAccess failures (it returns an error only for
|
||||||
|
// protocol-level failures or transport errors).
|
||||||
|
//
|
||||||
|
// A non-nil but empty entries slice is treated as a no-op and returns an empty result
|
||||||
|
// without a wire round-trip; pass nil to surface a clear "entries are required" error.
|
||||||
|
func (s *Session) WriteBulk(ctx context.Context, serverHandle int32, entries []*WriteBulkEntry) ([]*BulkWriteResult, error) {
|
||||||
|
if entries == nil {
|
||||||
|
return nil, errors.New("mxgateway: write bulk entries are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("write bulk entries", len(entries)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(entries) == 0 {
|
||||||
|
return []*BulkWriteResult{}, nil
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_WRITE_BULK,
|
||||||
|
Payload: &pb.MxCommand_WriteBulk{
|
||||||
|
WriteBulk: &pb.WriteBulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
Entries: entries,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetWriteBulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write2Bulk invokes MXAccess Write2 (timestamped) for each entry inside one gateway command.
|
||||||
|
//
|
||||||
|
// A non-nil but empty entries slice is treated as a no-op and returns an empty result
|
||||||
|
// without a wire round-trip; pass nil to surface a clear "entries are required" error.
|
||||||
|
func (s *Session) Write2Bulk(ctx context.Context, serverHandle int32, entries []*Write2BulkEntry) ([]*BulkWriteResult, error) {
|
||||||
|
if entries == nil {
|
||||||
|
return nil, errors.New("mxgateway: write2 bulk entries are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("write2 bulk entries", len(entries)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(entries) == 0 {
|
||||||
|
return []*BulkWriteResult{}, nil
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_WRITE2_BULK,
|
||||||
|
Payload: &pb.MxCommand_Write2Bulk{
|
||||||
|
Write2Bulk: &pb.Write2BulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
Entries: entries,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetWrite2Bulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteSecuredBulk invokes MXAccess WriteSecured for each entry. Credential-sensitive
|
||||||
|
// values must not be logged by callers; mirrors the single-item WriteSecured contract.
|
||||||
|
//
|
||||||
|
// A non-nil but empty entries slice is treated as a no-op and returns an empty result
|
||||||
|
// without a wire round-trip; pass nil to surface a clear "entries are required" error.
|
||||||
|
func (s *Session) WriteSecuredBulk(ctx context.Context, serverHandle int32, entries []*WriteSecuredBulkEntry) ([]*BulkWriteResult, error) {
|
||||||
|
if entries == nil {
|
||||||
|
return nil, errors.New("mxgateway: write-secured bulk entries are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("write-secured bulk entries", len(entries)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(entries) == 0 {
|
||||||
|
return []*BulkWriteResult{}, nil
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_WRITE_SECURED_BULK,
|
||||||
|
Payload: &pb.MxCommand_WriteSecuredBulk{
|
||||||
|
WriteSecuredBulk: &pb.WriteSecuredBulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
Entries: entries,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetWriteSecuredBulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteSecured2Bulk invokes MXAccess WriteSecured2 (timestamped) for each entry.
|
||||||
|
//
|
||||||
|
// A non-nil but empty entries slice is treated as a no-op and returns an empty result
|
||||||
|
// without a wire round-trip; pass nil to surface a clear "entries are required" error.
|
||||||
|
func (s *Session) WriteSecured2Bulk(ctx context.Context, serverHandle int32, entries []*WriteSecured2BulkEntry) ([]*BulkWriteResult, error) {
|
||||||
|
if entries == nil {
|
||||||
|
return nil, errors.New("mxgateway: write-secured2 bulk entries are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("write-secured2 bulk entries", len(entries)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(entries) == 0 {
|
||||||
|
return []*BulkWriteResult{}, nil
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_WRITE_SECURED2_BULK,
|
||||||
|
Payload: &pb.MxCommand_WriteSecured2Bulk{
|
||||||
|
WriteSecured2Bulk: &pb.WriteSecured2BulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
Entries: entries,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetWriteSecured2Bulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadBulk snapshots the current value of each requested tag.
|
||||||
|
//
|
||||||
|
// MXAccess COM has no synchronous Read; the worker satisfies this by returning the
|
||||||
|
// most recent cached OnDataChange value when the tag is already advised (WasCached=true),
|
||||||
|
// or by taking a full AddItem + Advise + wait + UnAdvise + RemoveItem snapshot lifecycle
|
||||||
|
// otherwise. timeout bounds the wait per tag in the snapshot case; pass zero to use the
|
||||||
|
// worker default. Per-tag failures (timeout, invalid tag) appear as BulkReadResult entries
|
||||||
|
// with WasSuccessful=false; the call never returns an error for per-tag MXAccess failures.
|
||||||
|
//
|
||||||
|
// A non-nil but empty tagAddresses slice is treated as a no-op and returns an empty
|
||||||
|
// result without a wire round-trip; pass nil to surface a clear "tag addresses are
|
||||||
|
// required" error.
|
||||||
|
func (s *Session) ReadBulk(ctx context.Context, serverHandle int32, tagAddresses []string, timeout time.Duration) ([]*BulkReadResult, error) {
|
||||||
|
if tagAddresses == nil {
|
||||||
|
return nil, errors.New("mxgateway: tag addresses are required")
|
||||||
|
}
|
||||||
|
if err := ensureBulkSize("tag addresses", len(tagAddresses)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(tagAddresses) == 0 {
|
||||||
|
return []*BulkReadResult{}, nil
|
||||||
|
}
|
||||||
|
var timeoutMs uint32
|
||||||
|
if timeout > 0 {
|
||||||
|
ms := timeout.Milliseconds()
|
||||||
|
if ms > int64(^uint32(0)) {
|
||||||
|
timeoutMs = ^uint32(0)
|
||||||
|
} else {
|
||||||
|
timeoutMs = uint32(ms)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reply, err := s.invokeCommand(ctx, &pb.MxCommand{
|
||||||
|
Kind: pb.MxCommandKind_MX_COMMAND_KIND_READ_BULK,
|
||||||
|
Payload: &pb.MxCommand_ReadBulk{
|
||||||
|
ReadBulk: &pb.ReadBulkCommand{
|
||||||
|
ServerHandle: serverHandle,
|
||||||
|
TagAddresses: tagAddresses,
|
||||||
|
TimeoutMs: timeoutMs,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return reply.GetReadBulk().GetResults(), nil
|
||||||
|
}
|
||||||
|
|
||||||
// Write invokes MXAccess Write.
|
// Write invokes MXAccess Write.
|
||||||
func (s *Session) Write(ctx context.Context, serverHandle, itemHandle int32, value *MxValue, userID int32) error {
|
func (s *Session) Write(ctx context.Context, serverHandle, itemHandle int32, value *MxValue, userID int32) error {
|
||||||
_, err := s.WriteRaw(ctx, serverHandle, itemHandle, value, userID)
|
_, err := s.WriteRaw(ctx, serverHandle, itemHandle, value, userID)
|
||||||
@@ -215,32 +588,99 @@ func (s *Session) Events(ctx context.Context) (<-chan EventResult, error) {
|
|||||||
|
|
||||||
// EventsAfter streams ordered session events after the given worker sequence.
|
// EventsAfter streams ordered session events after the given worker sequence.
|
||||||
func (s *Session) EventsAfter(ctx context.Context, afterWorkerSequence uint64) (<-chan EventResult, error) {
|
func (s *Session) EventsAfter(ctx context.Context, afterWorkerSequence uint64) (<-chan EventResult, error) {
|
||||||
stream, err := s.client.StreamEventsRaw(ctx, &pb.StreamEventsRequest{
|
subscription, err := s.subscribeEventsAfter(ctx, afterWorkerSequence, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return subscription.Events(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubscribeEvents starts an owned event subscription.
|
||||||
|
func (s *Session) SubscribeEvents(ctx context.Context) (*EventSubscription, error) {
|
||||||
|
return s.SubscribeEventsAfter(ctx, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubscribeEventsAfter starts an owned event subscription after the given worker sequence.
|
||||||
|
func (s *Session) SubscribeEventsAfter(ctx context.Context, afterWorkerSequence uint64) (*EventSubscription, error) {
|
||||||
|
return s.subscribeEventsAfter(ctx, afterWorkerSequence, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Session) subscribeEventsAfter(ctx context.Context, afterWorkerSequence uint64, cancelWhenResultBufferFull bool) (*EventSubscription, error) {
|
||||||
|
streamCtx, cancel := context.WithCancel(ctx)
|
||||||
|
stream, err := s.client.StreamEventsRaw(streamCtx, &pb.StreamEventsRequest{
|
||||||
SessionId: s.ID(),
|
SessionId: s.ID(),
|
||||||
AfterWorkerSequence: afterWorkerSequence,
|
AfterWorkerSequence: afterWorkerSequence,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
cancel()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
results := make(chan EventResult, 16)
|
results := make(chan EventResult, 16)
|
||||||
|
done := make(chan struct{})
|
||||||
go func() {
|
go func() {
|
||||||
defer close(results)
|
defer close(results)
|
||||||
|
defer close(done)
|
||||||
for {
|
for {
|
||||||
event, err := stream.Recv()
|
event, err := stream.Recv()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
results <- EventResult{Event: event}
|
if !sendEventResult(streamCtx, results, EventResult{Event: event}, cancelWhenResultBufferFull, cancel) {
|
||||||
|
return
|
||||||
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if err == io.EOF || status.Code(err) == codes.Canceled || ctx.Err() != nil {
|
if err == io.EOF || status.Code(err) == codes.Canceled || streamCtx.Err() != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
results <- EventResult{Err: &GatewayError{Op: "stream events", Err: err}}
|
sendEventResult(
|
||||||
|
streamCtx,
|
||||||
|
results,
|
||||||
|
EventResult{Err: &GatewayError{Op: "stream events", Err: err}},
|
||||||
|
cancelWhenResultBufferFull,
|
||||||
|
cancel)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return results, nil
|
return &EventSubscription{
|
||||||
|
results: results,
|
||||||
|
cancel: cancel,
|
||||||
|
done: done,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureBulkSize(name string, length int) error {
|
||||||
|
if length > maxBulkItems {
|
||||||
|
return fmt.Errorf("mxgateway: %s bulk commands are limited to %d item(s)", name, maxBulkItems)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendEventResult(
|
||||||
|
ctx context.Context,
|
||||||
|
results chan<- EventResult,
|
||||||
|
result EventResult,
|
||||||
|
cancelWhenBufferFull bool,
|
||||||
|
cancel context.CancelFunc,
|
||||||
|
) bool {
|
||||||
|
if cancelWhenBufferFull {
|
||||||
|
select {
|
||||||
|
case results <- result:
|
||||||
|
return true
|
||||||
|
case <-ctx.Done():
|
||||||
|
return false
|
||||||
|
default:
|
||||||
|
cancel()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case results <- result:
|
||||||
|
return true
|
||||||
|
case <-ctx.Done():
|
||||||
|
return false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Session) invokeCommand(ctx context.Context, command *MxCommand) (*MxCommandReply, error) {
|
func (s *Session) invokeCommand(ctx context.Context, command *MxCommand) (*MxCommandReply, error) {
|
||||||
|
|||||||
+182
-39
@@ -12,59 +12,202 @@ type RawEventStream = pb.MxAccessGateway_StreamEventsClient
|
|||||||
// Generated protobuf aliases keep raw contract access available from the public
|
// Generated protobuf aliases keep raw contract access available from the public
|
||||||
// mxgateway package while generated code remains under internal/generated.
|
// mxgateway package while generated code remains under internal/generated.
|
||||||
type (
|
type (
|
||||||
OpenSessionRequest = pb.OpenSessionRequest
|
// OpenSessionRequest is the gateway OpenSession request message.
|
||||||
OpenSessionReply = pb.OpenSessionReply
|
OpenSessionRequest = pb.OpenSessionRequest
|
||||||
|
// OpenSessionReply is the gateway OpenSession reply message.
|
||||||
|
OpenSessionReply = pb.OpenSessionReply
|
||||||
|
// CloseSessionRequest is the gateway CloseSession request message.
|
||||||
CloseSessionRequest = pb.CloseSessionRequest
|
CloseSessionRequest = pb.CloseSessionRequest
|
||||||
CloseSessionReply = pb.CloseSessionReply
|
// CloseSessionReply is the gateway CloseSession reply message.
|
||||||
|
CloseSessionReply = pb.CloseSessionReply
|
||||||
|
// StreamEventsRequest is the gateway StreamEvents request message.
|
||||||
StreamEventsRequest = pb.StreamEventsRequest
|
StreamEventsRequest = pb.StreamEventsRequest
|
||||||
MxCommandRequest = pb.MxCommandRequest
|
// MxCommandRequest carries one MXAccess command for Invoke.
|
||||||
MxCommandReply = pb.MxCommandReply
|
MxCommandRequest = pb.MxCommandRequest
|
||||||
MxCommand = pb.MxCommand
|
// MxCommandReply is the reply to an MXAccess command Invoke.
|
||||||
MxEvent = pb.MxEvent
|
MxCommandReply = pb.MxCommandReply
|
||||||
MxValue = pb.MxValue
|
// MxCommand is the discriminated union of MXAccess command payloads.
|
||||||
Value = pb.MxValue
|
MxCommand = pb.MxCommand
|
||||||
MxArray = pb.MxArray
|
// MxEvent is one ordered event delivered on a session event stream.
|
||||||
MxStatusProxy = pb.MxStatusProxy
|
MxEvent = pb.MxEvent
|
||||||
ProtocolStatus = pb.ProtocolStatus
|
// MxValue is the protobuf representation of an MXAccess value.
|
||||||
RegisterCommand = pb.RegisterCommand
|
MxValue = pb.MxValue
|
||||||
UnregisterCommand = pb.UnregisterCommand
|
// Value is an alias for MxValue retained for symmetry with other clients.
|
||||||
AddItemCommand = pb.AddItemCommand
|
Value = pb.MxValue
|
||||||
AddItem2Command = pb.AddItem2Command
|
// MxArray is the protobuf representation of an MXAccess array value.
|
||||||
AdviseCommand = pb.AdviseCommand
|
MxArray = pb.MxArray
|
||||||
WriteCommand = pb.WriteCommand
|
// MxStatusProxy mirrors the MXAccess MXSTATUS_PROXY structure.
|
||||||
Write2Command = pb.Write2Command
|
MxStatusProxy = pb.MxStatusProxy
|
||||||
RegisterReply = pb.RegisterReply
|
// ProtocolStatus is the gateway-level status carried on every reply.
|
||||||
AddItemReply = pb.AddItemReply
|
ProtocolStatus = pb.ProtocolStatus
|
||||||
AddItem2Reply = pb.AddItem2Reply
|
// RegisterCommand is the payload of an MXAccess Register command.
|
||||||
|
RegisterCommand = pb.RegisterCommand
|
||||||
|
// UnregisterCommand is the payload of an MXAccess Unregister command.
|
||||||
|
UnregisterCommand = pb.UnregisterCommand
|
||||||
|
// AddItemCommand is the payload of an MXAccess AddItem command.
|
||||||
|
AddItemCommand = pb.AddItemCommand
|
||||||
|
// AddItem2Command is the payload of an MXAccess AddItem2 command.
|
||||||
|
AddItem2Command = pb.AddItem2Command
|
||||||
|
// RemoveItemCommand is the payload of an MXAccess RemoveItem command.
|
||||||
|
RemoveItemCommand = pb.RemoveItemCommand
|
||||||
|
// AdviseCommand is the payload of an MXAccess Advise command.
|
||||||
|
AdviseCommand = pb.AdviseCommand
|
||||||
|
// UnAdviseCommand is the payload of an MXAccess UnAdvise command.
|
||||||
|
UnAdviseCommand = pb.UnAdviseCommand
|
||||||
|
// AddItemBulkCommand is the payload of an AddItem bulk command.
|
||||||
|
AddItemBulkCommand = pb.AddItemBulkCommand
|
||||||
|
// AdviseItemBulkCommand is the payload of an Advise bulk command.
|
||||||
|
AdviseItemBulkCommand = pb.AdviseItemBulkCommand
|
||||||
|
// RemoveItemBulkCommand is the payload of a RemoveItem bulk command.
|
||||||
|
RemoveItemBulkCommand = pb.RemoveItemBulkCommand
|
||||||
|
// UnAdviseItemBulkCommand is the payload of an UnAdvise bulk command.
|
||||||
|
UnAdviseItemBulkCommand = pb.UnAdviseItemBulkCommand
|
||||||
|
// SubscribeBulkCommand combines AddItem and Advise for a list of tags.
|
||||||
|
SubscribeBulkCommand = pb.SubscribeBulkCommand
|
||||||
|
// UnsubscribeBulkCommand combines UnAdvise and RemoveItem for a list of items.
|
||||||
|
UnsubscribeBulkCommand = pb.UnsubscribeBulkCommand
|
||||||
|
// WriteCommand is the payload of an MXAccess Write command.
|
||||||
|
WriteCommand = pb.WriteCommand
|
||||||
|
// Write2Command is the payload of an MXAccess Write2 command.
|
||||||
|
Write2Command = pb.Write2Command
|
||||||
|
// WriteBulkCommand is the payload of a bulk Write command.
|
||||||
|
WriteBulkCommand = pb.WriteBulkCommand
|
||||||
|
// WriteBulkEntry is one entry inside a WriteBulkCommand.
|
||||||
|
WriteBulkEntry = pb.WriteBulkEntry
|
||||||
|
// Write2BulkCommand is the payload of a bulk Write2 (timestamped) command.
|
||||||
|
Write2BulkCommand = pb.Write2BulkCommand
|
||||||
|
// Write2BulkEntry is one entry inside a Write2BulkCommand.
|
||||||
|
Write2BulkEntry = pb.Write2BulkEntry
|
||||||
|
// WriteSecuredBulkCommand is the payload of a bulk WriteSecured command.
|
||||||
|
WriteSecuredBulkCommand = pb.WriteSecuredBulkCommand
|
||||||
|
// WriteSecuredBulkEntry is one entry inside a WriteSecuredBulkCommand.
|
||||||
|
WriteSecuredBulkEntry = pb.WriteSecuredBulkEntry
|
||||||
|
// WriteSecured2BulkCommand is the payload of a bulk WriteSecured2 (timestamped) command.
|
||||||
|
WriteSecured2BulkCommand = pb.WriteSecured2BulkCommand
|
||||||
|
// WriteSecured2BulkEntry is one entry inside a WriteSecured2BulkCommand.
|
||||||
|
WriteSecured2BulkEntry = pb.WriteSecured2BulkEntry
|
||||||
|
// ReadBulkCommand is the payload of a bulk Read snapshot command.
|
||||||
|
ReadBulkCommand = pb.ReadBulkCommand
|
||||||
|
// BulkWriteReply aggregates BulkWriteResult entries for a bulk write command.
|
||||||
|
BulkWriteReply = pb.BulkWriteReply
|
||||||
|
// BulkWriteResult is one entry in a bulk write reply list.
|
||||||
|
BulkWriteResult = pb.BulkWriteResult
|
||||||
|
// BulkReadReply aggregates BulkReadResult entries for a bulk read command.
|
||||||
|
BulkReadReply = pb.BulkReadReply
|
||||||
|
// BulkReadResult is one entry in a bulk read reply list.
|
||||||
|
BulkReadResult = pb.BulkReadResult
|
||||||
|
// RegisterReply carries the ServerHandle returned by Register.
|
||||||
|
RegisterReply = pb.RegisterReply
|
||||||
|
// AddItemReply carries the ItemHandle returned by AddItem.
|
||||||
|
AddItemReply = pb.AddItemReply
|
||||||
|
// AddItem2Reply carries the ItemHandle returned by AddItem2.
|
||||||
|
AddItem2Reply = pb.AddItem2Reply
|
||||||
|
// SubscribeResult is one entry in a bulk command result list.
|
||||||
|
SubscribeResult = pb.SubscribeResult
|
||||||
|
// BulkSubscribeReply aggregates SubscribeResult entries for a bulk command.
|
||||||
|
BulkSubscribeReply = pb.BulkSubscribeReply
|
||||||
|
// AcknowledgeAlarmRequest is the gateway AcknowledgeAlarm request message.
|
||||||
|
AcknowledgeAlarmRequest = pb.AcknowledgeAlarmRequest
|
||||||
|
// AcknowledgeAlarmReply is the gateway AcknowledgeAlarm reply message.
|
||||||
|
AcknowledgeAlarmReply = pb.AcknowledgeAlarmReply
|
||||||
|
// QueryActiveAlarmsRequest is the gateway QueryActiveAlarms request message.
|
||||||
|
QueryActiveAlarmsRequest = pb.QueryActiveAlarmsRequest
|
||||||
|
// StreamAlarmsRequest is the gateway StreamAlarms request message.
|
||||||
|
StreamAlarmsRequest = pb.StreamAlarmsRequest
|
||||||
|
// AlarmFeedMessage is one message on the StreamAlarms feed — an
|
||||||
|
// active-alarm snapshot row, a snapshot-complete sentinel, or a transition.
|
||||||
|
AlarmFeedMessage = pb.AlarmFeedMessage
|
||||||
|
// ActiveAlarmSnapshot is one row in a ConditionRefresh stream.
|
||||||
|
ActiveAlarmSnapshot = pb.ActiveAlarmSnapshot
|
||||||
|
// OnAlarmTransitionEvent is the body carried by alarm-transition MxEvents.
|
||||||
|
OnAlarmTransitionEvent = pb.OnAlarmTransitionEvent
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// AlarmTransitionKind discriminates raise / acknowledge / clear / retrigger
|
||||||
|
// transitions on an OnAlarmTransitionEvent.
|
||||||
|
type AlarmTransitionKind = pb.AlarmTransitionKind
|
||||||
|
|
||||||
|
// AlarmConditionState reports the current state of an active alarm in a
|
||||||
|
// ConditionRefresh snapshot.
|
||||||
|
type AlarmConditionState = pb.AlarmConditionState
|
||||||
|
|
||||||
|
// QueryActiveAlarmsClient is the generated server-streaming client for the
|
||||||
|
// QueryActiveAlarms RPC.
|
||||||
|
type QueryActiveAlarmsClient = pb.MxAccessGateway_QueryActiveAlarmsClient
|
||||||
|
|
||||||
|
// StreamAlarmsClient is the generated server-streaming client for the
|
||||||
|
// StreamAlarms RPC.
|
||||||
|
type StreamAlarmsClient = pb.MxAccessGateway_StreamAlarmsClient
|
||||||
|
|
||||||
|
// Enumerations from the generated contract re-exported for client callers.
|
||||||
type (
|
type (
|
||||||
MxCommandKind = pb.MxCommandKind
|
// MxCommandKind discriminates which MXAccess command an MxCommand carries.
|
||||||
MxDataType = pb.MxDataType
|
MxCommandKind = pb.MxCommandKind
|
||||||
MxEventFamily = pb.MxEventFamily
|
// MxDataType is the MXAccess data type tag on values and arrays.
|
||||||
MxStatusCategory = pb.MxStatusCategory
|
MxDataType = pb.MxDataType
|
||||||
MxStatusSource = pb.MxStatusSource
|
// MxEventFamily groups MXAccess events by source category.
|
||||||
|
MxEventFamily = pb.MxEventFamily
|
||||||
|
// MxStatusCategory classifies MXSTATUS_PROXY entries.
|
||||||
|
MxStatusCategory = pb.MxStatusCategory
|
||||||
|
// MxStatusSource identifies the originator of a status entry.
|
||||||
|
MxStatusSource = pb.MxStatusSource
|
||||||
|
// ProtocolStatusCode enumerates gateway-level status codes.
|
||||||
ProtocolStatusCode = pb.ProtocolStatusCode
|
ProtocolStatusCode = pb.ProtocolStatusCode
|
||||||
SessionState = pb.SessionState
|
// SessionState enumerates gateway session lifecycle states.
|
||||||
|
SessionState = pb.SessionState
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// MXAccess command kind, data type, and protocol status constants surfaced
|
||||||
|
// from the generated contract.
|
||||||
const (
|
const (
|
||||||
CommandKindRegister = pb.MxCommandKind_MX_COMMAND_KIND_REGISTER
|
// CommandKindRegister selects the MXAccess Register command.
|
||||||
|
CommandKindRegister = pb.MxCommandKind_MX_COMMAND_KIND_REGISTER
|
||||||
|
// CommandKindUnregister selects the MXAccess Unregister command.
|
||||||
CommandKindUnregister = pb.MxCommandKind_MX_COMMAND_KIND_UNREGISTER
|
CommandKindUnregister = pb.MxCommandKind_MX_COMMAND_KIND_UNREGISTER
|
||||||
CommandKindAddItem = pb.MxCommandKind_MX_COMMAND_KIND_ADD_ITEM
|
// CommandKindAddItem selects the MXAccess AddItem command.
|
||||||
CommandKindAddItem2 = pb.MxCommandKind_MX_COMMAND_KIND_ADD_ITEM2
|
CommandKindAddItem = pb.MxCommandKind_MX_COMMAND_KIND_ADD_ITEM
|
||||||
CommandKindAdvise = pb.MxCommandKind_MX_COMMAND_KIND_ADVISE
|
// CommandKindAddItem2 selects the MXAccess AddItem2 command.
|
||||||
CommandKindWrite = pb.MxCommandKind_MX_COMMAND_KIND_WRITE
|
CommandKindAddItem2 = pb.MxCommandKind_MX_COMMAND_KIND_ADD_ITEM2
|
||||||
CommandKindWrite2 = pb.MxCommandKind_MX_COMMAND_KIND_WRITE2
|
// CommandKindRemoveItem selects the MXAccess RemoveItem command.
|
||||||
|
CommandKindRemoveItem = pb.MxCommandKind_MX_COMMAND_KIND_REMOVE_ITEM
|
||||||
|
// CommandKindAdvise selects the MXAccess Advise command.
|
||||||
|
CommandKindAdvise = pb.MxCommandKind_MX_COMMAND_KIND_ADVISE
|
||||||
|
// CommandKindUnAdvise selects the MXAccess UnAdvise command.
|
||||||
|
CommandKindUnAdvise = pb.MxCommandKind_MX_COMMAND_KIND_UN_ADVISE
|
||||||
|
// CommandKindAddItemBulk selects the AddItem bulk command.
|
||||||
|
CommandKindAddItemBulk = pb.MxCommandKind_MX_COMMAND_KIND_ADD_ITEM_BULK
|
||||||
|
// CommandKindAdviseItemBulk selects the Advise bulk command.
|
||||||
|
CommandKindAdviseItemBulk = pb.MxCommandKind_MX_COMMAND_KIND_ADVISE_ITEM_BULK
|
||||||
|
// CommandKindRemoveItemBulk selects the RemoveItem bulk command.
|
||||||
|
CommandKindRemoveItemBulk = pb.MxCommandKind_MX_COMMAND_KIND_REMOVE_ITEM_BULK
|
||||||
|
// CommandKindUnAdviseItemBulk selects the UnAdvise bulk command.
|
||||||
|
CommandKindUnAdviseItemBulk = pb.MxCommandKind_MX_COMMAND_KIND_UN_ADVISE_ITEM_BULK
|
||||||
|
// CommandKindSubscribeBulk selects the AddItem+Advise combined bulk command.
|
||||||
|
CommandKindSubscribeBulk = pb.MxCommandKind_MX_COMMAND_KIND_SUBSCRIBE_BULK
|
||||||
|
// CommandKindUnsubscribeBulk selects the UnAdvise+RemoveItem combined bulk command.
|
||||||
|
CommandKindUnsubscribeBulk = pb.MxCommandKind_MX_COMMAND_KIND_UNSUBSCRIBE_BULK
|
||||||
|
// CommandKindWrite selects the MXAccess Write command.
|
||||||
|
CommandKindWrite = pb.MxCommandKind_MX_COMMAND_KIND_WRITE
|
||||||
|
// CommandKindWrite2 selects the MXAccess Write2 command.
|
||||||
|
CommandKindWrite2 = pb.MxCommandKind_MX_COMMAND_KIND_WRITE2
|
||||||
|
|
||||||
|
// DataTypeUnknown denotes an unrecognized MXAccess data type.
|
||||||
DataTypeUnknown = pb.MxDataType_MX_DATA_TYPE_UNKNOWN
|
DataTypeUnknown = pb.MxDataType_MX_DATA_TYPE_UNKNOWN
|
||||||
|
// DataTypeBoolean denotes an MXAccess Boolean value.
|
||||||
DataTypeBoolean = pb.MxDataType_MX_DATA_TYPE_BOOLEAN
|
DataTypeBoolean = pb.MxDataType_MX_DATA_TYPE_BOOLEAN
|
||||||
|
// DataTypeInteger denotes an MXAccess Integer value.
|
||||||
DataTypeInteger = pb.MxDataType_MX_DATA_TYPE_INTEGER
|
DataTypeInteger = pb.MxDataType_MX_DATA_TYPE_INTEGER
|
||||||
DataTypeFloat = pb.MxDataType_MX_DATA_TYPE_FLOAT
|
// DataTypeFloat denotes an MXAccess Float (single precision) value.
|
||||||
DataTypeDouble = pb.MxDataType_MX_DATA_TYPE_DOUBLE
|
DataTypeFloat = pb.MxDataType_MX_DATA_TYPE_FLOAT
|
||||||
DataTypeString = pb.MxDataType_MX_DATA_TYPE_STRING
|
// DataTypeDouble denotes an MXAccess Double (double precision) value.
|
||||||
DataTypeTime = pb.MxDataType_MX_DATA_TYPE_TIME
|
DataTypeDouble = pb.MxDataType_MX_DATA_TYPE_DOUBLE
|
||||||
|
// DataTypeString denotes an MXAccess String value.
|
||||||
|
DataTypeString = pb.MxDataType_MX_DATA_TYPE_STRING
|
||||||
|
// DataTypeTime denotes an MXAccess timestamp value.
|
||||||
|
DataTypeTime = pb.MxDataType_MX_DATA_TYPE_TIME
|
||||||
|
|
||||||
ProtocolStatusOK = pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK
|
// ProtocolStatusOK indicates the gateway processed the request successfully.
|
||||||
|
ProtocolStatusOK = pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_OK
|
||||||
|
// ProtocolStatusMxAccessFailure indicates the worker reported an MXAccess failure.
|
||||||
ProtocolStatusMxAccessFailure = pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_MXACCESS_FAILURE
|
ProtocolStatusMxAccessFailure = pb.ProtocolStatusCode_PROTOCOL_STATUS_CODE_MXACCESS_FAILURE
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ const (
|
|||||||
|
|
||||||
// GatewayProtocolVersion matches GatewayContractInfo.GatewayProtocolVersion
|
// GatewayProtocolVersion matches GatewayContractInfo.GatewayProtocolVersion
|
||||||
// in the shared .NET contracts.
|
// in the shared .NET contracts.
|
||||||
GatewayProtocolVersion uint32 = 1
|
GatewayProtocolVersion uint32 = 3
|
||||||
|
|
||||||
// WorkerProtocolVersion matches GatewayContractInfo.WorkerProtocolVersion
|
// WorkerProtocolVersion matches GatewayContractInfo.WorkerProtocolVersion
|
||||||
// and is exposed for fake-worker and parity tests.
|
// and is exposed for fake-worker and parity tests.
|
||||||
|
|||||||
@@ -5,8 +5,8 @@
|
|||||||
Provide a Java client library for MXAccess Gateway, plus a test CLI and unit
|
Provide a Java client library for MXAccess Gateway, plus a test CLI and unit
|
||||||
tests. The Java client should work for JVM services and operator tooling.
|
tests. The Java client should work for JVM services and operator tooling.
|
||||||
|
|
||||||
Follow the [Java Style Guide](./style-guides/JavaStyleGuide.md) for handwritten
|
Follow the [Java Style Guide](../../docs/style-guides/JavaStyleGuide.md) for handwritten
|
||||||
code and the [Protobuf Style Guide](./style-guides/ProtobufStyleGuide.md) for
|
code and the [Protobuf Style Guide](../../docs/style-guides/ProtobufStyleGuide.md) for
|
||||||
generated contract inputs.
|
generated contract inputs.
|
||||||
|
|
||||||
## Build Layout
|
## Build Layout
|
||||||
@@ -18,13 +18,13 @@ clients/java/
|
|||||||
settings.gradle
|
settings.gradle
|
||||||
build.gradle
|
build.gradle
|
||||||
src/main/generated/
|
src/main/generated/
|
||||||
mxgateway-client/
|
zb-mom-ww-mxgateway-client/
|
||||||
build.gradle
|
build.gradle
|
||||||
src/main/java/com/dohertylan/mxgateway/client/
|
src/main/java/com/zb/mom/ww/mxgateway/client/
|
||||||
src/test/java/com/dohertylan/mxgateway/client/
|
src/test/java/com/zb/mom/ww/mxgateway/client/
|
||||||
mxgateway-cli/
|
zb-mom-ww-mxgateway-cli/
|
||||||
build.gradle
|
build.gradle
|
||||||
src/main/java/com/dohertylan/mxgateway/cli/
|
src/main/java/com/zb/mom/ww/mxgateway/cli/
|
||||||
```
|
```
|
||||||
|
|
||||||
Alternative Maven layout is acceptable if the repo standardizes on Maven.
|
Alternative Maven layout is acceptable if the repo standardizes on Maven.
|
||||||
@@ -64,6 +64,12 @@ public final class MxGatewaySession implements AutoCloseable {
|
|||||||
public int addItem(int serverHandle, String item);
|
public int addItem(int serverHandle, String item);
|
||||||
public int addItem2(int serverHandle, String item, String context);
|
public int addItem2(int serverHandle, String item, String context);
|
||||||
public void advise(int serverHandle, int itemHandle);
|
public void advise(int serverHandle, int itemHandle);
|
||||||
|
public List<SubscribeResult> addItemBulk(int serverHandle, List<String> tagAddresses);
|
||||||
|
public List<SubscribeResult> adviseItemBulk(int serverHandle, List<Integer> itemHandles);
|
||||||
|
public List<SubscribeResult> removeItemBulk(int serverHandle, List<Integer> itemHandles);
|
||||||
|
public List<SubscribeResult> unAdviseItemBulk(int serverHandle, List<Integer> itemHandles);
|
||||||
|
public List<SubscribeResult> subscribeBulk(int serverHandle, List<String> tagAddresses);
|
||||||
|
public List<SubscribeResult> unsubscribeBulk(int serverHandle, List<Integer> itemHandles);
|
||||||
public void write(int serverHandle, int itemHandle, MxValue value, int userId);
|
public void write(int serverHandle, int itemHandle, MxValue value, int userId);
|
||||||
public Iterator<MxEvent> streamEvents();
|
public Iterator<MxEvent> streamEvents();
|
||||||
public void streamEventsAsync(StreamObserver<MxEvent> observer);
|
public void streamEventsAsync(StreamObserver<MxEvent> observer);
|
||||||
@@ -186,8 +192,8 @@ stream for bounded time, and close.
|
|||||||
|
|
||||||
Publish library and CLI separately:
|
Publish library and CLI separately:
|
||||||
|
|
||||||
- `mxgateway-client` jar,
|
- `zb-mom-ww-mxgateway-client` jar,
|
||||||
- `mxgateway-cli` runnable distribution.
|
- `zb-mom-ww-mxgateway-cli` runnable distribution.
|
||||||
|
|
||||||
Generated protobuf code should be produced during the build from shared proto
|
Generated protobuf code should be produced during the build from shared proto
|
||||||
files and should not be hand-edited.
|
files and should not be hand-edited.
|
||||||
@@ -200,7 +206,14 @@ Run the Java scaffold checks from `clients/java`:
|
|||||||
gradle test
|
gradle test
|
||||||
```
|
```
|
||||||
|
|
||||||
The `mxgateway-client` project generates the gateway and worker protobuf/gRPC
|
The `zb-mom-ww-mxgateway-client` project generates the gateway and worker
|
||||||
bindings into `src/main/generated`, compiles the generated contracts, and runs
|
protobuf/gRPC bindings into `src/main/generated`, compiles the generated
|
||||||
JUnit 5 tests. The `mxgateway-cli` project builds a Picocli-based `mxgw-java`
|
contracts, and runs JUnit 5 tests. The `zb-mom-ww-mxgateway-cli` project
|
||||||
entry point for later command implementation.
|
builds a Picocli-based `mxgw-java` entry point for later command implementation.
|
||||||
|
|
||||||
|
## Related Documentation
|
||||||
|
|
||||||
|
- [Client Libraries Detailed Design](../../docs/ClientLibrariesDesign.md)
|
||||||
|
- [Client Proto Generation](../../docs/ClientProtoGeneration.md)
|
||||||
|
- [Client Packaging](../../docs/ClientPackaging.md)
|
||||||
|
- [Java Style Guide](../../docs/style-guides/JavaStyleGuide.md)
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user