Sonde v1.1.0
Embeddable Model Context Protocol server for Qt applications
Loading...
Searching...
No Matches
Sonde::ServerPrivate Class Reference

Implementation of Server: registries, sessions, dispatch and events. More...

#include <server_p.h>

Classes

struct  ToolEntry
 A registered tool. More...
struct  ResourceEntry
 A registered resource. More...

Public Member Functions

 ServerPrivate (Server *server)
 Sets defaults from the application and wires the coalescing timers.
 ~ServerPrivate ()
 Destroys the implementation.
void ensureIoThread ()
 Starts the worker thread if the mode asks for one and it isn't running yet.
void runOnIo (const std::function< void()> &fn) const
 Runs fn on the sessions' thread and waits for it (inline if already there).
QObject * ioObject () const
 The object timers for the sessions' thread are parented to.
void stopIoThread ()
 Stops the worker, after the transports and sessions on it are gone.
qint64 guiUnresponsiveMs () const
 How long the server's thread hasn't run its heartbeat (0 in ServerThread mode, where anyone asking is on that thread).
QString notRespondingMessage (const QString &what) const
 The error for something the server's thread didn't start in time.
void armStartTimeout (const std::shared_ptr< ToolCallPrivate > &call) const
 In WorkerThread mode, finishes call with notRespondingMessage() if its handler hasn't started within limits.guiResponseTimeout.
void addThreadSafeTool (const ToolDefinition &definition, AsyncToolHandler handler)
 Registers a tool whose handler runs on the sessions' thread, so it answers while the server's thread is blocked.
void addThreadSafeResource (const ResourceDefinition &definition, ResourceReader reader)
 Registers a resource whose reader runs on the sessions' thread, like addThreadSafeTool().
ToolResult appStatus () const
 The app_status result. Call on the sessions' thread.
QUrl httpUrlOnIo () const
 Server::httpUrl(), on the sessions' thread.
void publishCatalog ()
 Builds a new Catalog from the registries and makes it the current one.
std::shared_ptr< const Catalog > currentCatalog () const
 The current Catalog. Safe from any thread.
SessionPtr createSession (const QString &transport)
 Creates and registers a session for transport.
void endSession (const QString &id)
 Ends a session: cancels its calls, closes its stream, emits sessionEnded.
void closeSession (const QString &id)
 endSession(), and closes its connection: for a session the server ends (Server::endSession(), a refused client), not one whose client went.
void handleInitializeRequest (const SessionPtr &session, const QJsonValue &id, const QJsonObject &params, const ReplyFunction &reply)
 Answers initialize, after asking the application's approval first if it set one and this is the session's first (design 0033).
void admit (Session &session) const
 Lets session in: its requests are answered from now on, and sessionStarted is emitted.
void handleMessage (const SessionPtr &session, const QJsonObject &message, const ReplyFunction &reply)
 Dispatches one JSON-RPC message.
void notify (Session &session, const QString &method, const QJsonObject &params)
 Sends a notification on a session's stream (dropped if it has none).
void broadcast (const QString &method, const QJsonObject &params)
 Sends a notification to every initialized session.
void scheduleListChanged (const QString &method)
 Queues a list_changed notification, coalescing bursts of changes.
void handleNotification (Session &session, const QString &method, const QJsonObject &params)
 Handles a notification (initialized, cancelled; others are ignored).
QJsonObject handleRequest (Session &session, const QString &method, const QJsonValue &id, const QJsonObject &params)
 Handles a request answered at once (everything but tools/call).
QJsonObject handleInitialize (Session &session, const QJsonObject &params) const
 Handles initialize: negotiates the version and records the client.
void handleToolsCall (const SessionPtr &session, const QJsonValue &id, const QJsonObject &params, const ReplyFunction &reply) const
 Handles tools/call: checks the tool and the arguments against the catalog, creates the call, and starts it with startToolCall().
void startToolCall (const std::shared_ptr< ToolCallPrivate > &call) const
 Runs the handler of call on the server's thread: looks it up in the registry (the tool may have gone since the catalog was read) and creates the call's context.
void startResourceRead (const QJsonValue &id, const QJsonObject &params, const ReplyFunction &reply)
 Answers resources/read: on this thread for a thread-safe resource, otherwise from the server's thread, with the start timeout.
QJsonObject handleResourcesRead (const QJsonValue &id, const QJsonObject &params) const
 Handles resources/read and returns the full response.
void updateStackSampling ()
 Starts or stops the stack samples of the stalls sources, as the setting, the environment and listening say.
std::pair< std::vector< std::shared_ptr< Detail::StackSampler > >, QString > stackSamplers () const
 The samplers that are running, and why there are none if so; any thread.
void describeStackSampling (QString &text, QJsonObject &fields) const
 The app_status lines and fields about stack samples; any thread.
void notifyResourceUpdated (const QString &uri)
 Server::notifyResourceUpdated(), from any thread: the notifications are sent on the sessions' thread.
void sendLogMessage (LogLevel level, const QString &logger, const QJsonValue &data)
 Server::sendLogMessage(), from any thread: the notifications are sent on the sessions' thread.
void flushEvents ()
 The flush: sends what the buffer has pending, on the sessions' thread.
void registerEventTools ()
 (Re)registers event_read/event_wait with the current source list.
ToolResult eventsRead (const QJsonObject &args) const
 The event_read tool.
void eventsWait (const ToolCall &call) const
 The event_wait tool: answers from the buffer, or registers a Waiter with a timeout.
QList< Event > queryEvents (const EventFilter &filter, int limit, bool newest) const
 Matching events from the buffer.
quint64 lastSequence () const
 Sequence number of the newest event so far (0 if none).

Static Public Member Functions

static ServerPrivate * get (Server *server)
 The implementation of server (for internal code such as the fuzzers).
static qint64 nowMs ()
 Milliseconds on a monotonic clock, comparable between threads.
static QJsonObject resourceResponse (const QJsonValue &id, const ResourceDefinition &definition, const ResourceContents &contents)
 The resources/read response for contents of the resource definition.
static QString formatEvents (const QList< Event > &list)
 One Event::toLine() per line.

Public Attributes

Server * q
 Public object.
std::shared_ptr< HomeLink > homeLink
 To the server's thread; cleared in ~Server.
ServerThreading threading = ServerThreading::ServerThread
 Chosen by the constructor.
std::unique_ptr< QThread > ioThread
 The worker, in WorkerThread mode once started.
QObject * ioContext = nullptr
 Lives on the worker: the target of ioLink, parent of timers.
std::shared_ptr< HomeLink > ioLink
 To the thread that owns the transports and sessions: the worker in WorkerThread mode, otherwise the same as homeLink.
std::atomic< int > sessionCounter = 0
 sessions.size(), readable from any thread.
std::atomic< qint64 > lastGuiTickMs = 0
 When the heartbeat last ran on the server's thread.
QString name
 serverInfo name.
QString version
 serverInfo version.
QString instructions
 initialize instructions.
QMap< QString, ToolEntry > tools
 Tools by name.
QMap< QString, ResourceEntry > resources
 Resources by URI.
QHash< QString, SessionPtr > sessions
 Live sessions by id.
ServerLimits limits
 Resource limits.
std::mutex catalogMutex
 Guards catalog.
std::shared_ptr< const Catalog > catalog
 The current snapshot (replaced, never changed).
std::unique_ptr< HttpTransport > http
 HTTP transport, if listening.
QString httpToken
 Bearer token for HTTP.
std::unique_ptr< LocalTransport > local
 Local socket transport, if listening.
SessionApproval approval
 Asked before a client is let in (server's thread).
std::atomic< bool > hasApproval { false }
 Whether approval is set (any thread).
QSet< QString > pendingListChanged
 list_changed methods waiting to be sent (sessions' thread).
QList< QPointer< EventSource > > sources
 Added event sources (server's thread).
StackSampling stackSampling = StackSampling::DuringStalls
 setStackSampling().
QList< QPointer< StallEventSource > > stallSources
 The stalls sources added (server's thread).
std::mutex samplersMutex
 Guards samplers and samplingNote.
std::vector< std::shared_ptr< Detail::StackSampler > > samplers
 Running, for app_status.
QString samplingNote
 Why no sampler runs, if none does.
std::shared_ptr< EventBuffer > eventBuffer = std::make_shared<EventBuffer>()
 The buffer; shared with the sources' connections, which may outlive us briefly on other threads.
QSet< QString > dirtyEventResources
 events:// URIs with unsent updates (sessions' thread).
bool eventResourcesScheduled = false
 Whether their throttle timer runs (sessions' thread).

Detailed Description

Implementation of Server: registries, sessions, dispatch and events.

Member Function Documentation

◆ addThreadSafeResource()

void Sonde::ServerPrivate::addThreadSafeResource ( const ResourceDefinition & definition,
ResourceReader reader )

Registers a resource whose reader runs on the sessions' thread, like addThreadSafeTool().

It must not touch GUI objects.

◆ addThreadSafeTool()

void Sonde::ServerPrivate::addThreadSafeTool ( const ToolDefinition & definition,
AsyncToolHandler handler )

Registers a tool whose handler runs on the sessions' thread, so it answers while the server's thread is blocked.

It must not touch GUI objects.

◆ admit()

void Sonde::ServerPrivate::admit ( Session & session) const

Lets session in: its requests are answered from now on, and sessionStarted is emitted.

Sessions' thread.

◆ createSession()

SessionPtr Sonde::ServerPrivate::createSession ( const QString & transport)

Creates and registers a session for transport.

Returns
The session, or nullptr if limits.maxSessions has been reached.

◆ guiUnresponsiveMs()

qint64 Sonde::ServerPrivate::guiUnresponsiveMs ( ) const

How long the server's thread hasn't run its heartbeat (0 in ServerThread mode, where anyone asking is on that thread).

Safe from any thread.

◆ handleInitializeRequest()

void Sonde::ServerPrivate::handleInitializeRequest ( const SessionPtr & session,
const QJsonValue & id,
const QJsonObject & params,
const ReplyFunction & reply )

Answers initialize, after asking the application's approval first if it set one and this is the session's first (design 0033).

Sessions' thread.

◆ handleMessage()

void Sonde::ServerPrivate::handleMessage ( const SessionPtr & session,
const QJsonObject & message,
const ReplyFunction & reply )

Dispatches one JSON-RPC message.

Parameters
sessionThe sending session.
messageThe message.
replyReceives the response; required exactly when JsonRpc::expectsResponse().

◆ handleRequest()

QJsonObject Sonde::ServerPrivate::handleRequest ( Session & session,
const QString & method,
const QJsonValue & id,
const QJsonObject & params )

Handles a request answered at once (everything but tools/call).

Returns
The full response.

◆ publishCatalog()

void Sonde::ServerPrivate::publishCatalog ( )

Builds a new Catalog from the registries and makes it the current one.

Call (on the server's thread) after every change to them.

◆ queryEvents()

QList< Event > Sonde::ServerPrivate::queryEvents ( const EventFilter & filter,
int limit,
bool newest ) const
inline

Matching events from the buffer.

Thread-safe.

Parameters
filterThe filter.
limitMaximum number of events.
newestTake the newest matches (otherwise the oldest after filter.since).
Returns
The events, oldest first.

◆ runOnIo()

void Sonde::ServerPrivate::runOnIo ( const std::function< void()> & fn) const

Runs fn on the sessions' thread and waits for it (inline if already there).

Only the server's thread may wait for the worker, never the reverse.

◆ startToolCall()

void Sonde::ServerPrivate::startToolCall ( const std::shared_ptr< ToolCallPrivate > & call) const

Runs the handler of call on the server's thread: looks it up in the registry (the tool may have gone since the catalog was read) and creates the call's context.

Does nothing for a call cancelled meanwhile.

◆ updateStackSampling()

void Sonde::ServerPrivate::updateStackSampling ( )

Starts or stops the stack samples of the stalls sources, as the setting, the environment and listening say.

Server's thread.


The documentation for this class was generated from the following files: