\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#411: Improved Channel Introspection via "chan info"}
\date{August 31, 2012}
\author{Pawel Salawa}
\urlstyle{sf}
\setlength{\parskip}{1ex}
\setlength{\parindent}{0pt}
\def\tipversion$#1${\texttt{\$#1\$}}
\def\tiplangle#1{\ensuremath{<}}
\def\tiprangle#1{\ensuremath{>}}
\def\tipbar#1{\ensuremath{|}}
\def\tipmail#1#2{\(\langle\){\small\expandafter\url{#1@#2}}\(\rangle\)}
\ifx\pdfoutput\undefined
\newcommand{\tipimage}[2]{\typeout{Make sure you download #1.eps}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.eps}}{\includegraphics[width=0.8\textwidth]{#1.eps}}}
\newcommand{\tipxref}[1]{}
\newcommand{\tipxrefend}{}
\else
\newcommand{\tipimage}[2]{\typeout{Make sure you create #1.pdf}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.pdf}}{\includegraphics[width=0.8\textwidth]{#1.pdf}}}
\pdfcatalog{/PageMode /UseOutlines}
\newcommand{\tipxref}[1]{\pdfannotlink attr {/C [0.5 0.5 1.0] /Border [0 0 1]} goto name {#1}}
\newcommand{\tipxrefend}{\pdfendlink}
\fi
\newenvironment{tipabstract}{\begin{abstract}}{\end{abstract}}
\begin{document}\maketitle
\begin{center}\begin{tabularx}{\linewidth}{|r@{: }X|}\hline
\textbf{TIP \#411}&\textbf{Improved Channel Introspection via "chan info"}\\\hline
Author&

Pawel Salawa \tipmail{pawelsalawa}{gmail.com}
\\
Created&Friday, \(\text{31}^{\text{st}}\) August 2012\\
Type&Project\\
Tcl Version&\(8.7\)\\
State&Draft\\
Vote&Pending\\
Version&\tipversion$Revision: 1.4 $\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This document describes new subcommand for \textbf{chan}, \textbf{chan info}, that provides a unified interface to deeper introspection of information about a particular channel.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

When working with Tcl channels sometimes it happens that we got the channel, but we don't know if it's a file channel, socket, or reflected channel. This information can be very useful. Also some additional information, depending of the channel type, like file path for file channel, host and port for sockets (it's already available, but could get unified within new \textbf{chan} subcommand), or any metadata provided by reflected channels.

An example where it could be used is the package with an API that accepts just a channel on input call and the inside routines need to do something with the file (in file system), so they have to learn the name of the file related to given channel.

\section{Specification}

A new subcommand for \textbf{chan} is introduced:

\begin{quote}
\textbf{chan info} \textit{channelId}
\end{quote}

Also a new optional command is introduced for reflected channels API:

\begin{quote}
\textit{cmdPrefix} \textbf{chaninfo} \textit{channelId}
\end{quote}

\subsection{The info Subcommand of chan}

The \textbf{chan info} command will take a single mandatory argument, \textit{channelId}, which will be the name of a channel to retrieve information about. This operation will always fail in a safe interpreter. The result of the new \textbf{chan info} command would be a dictionary with following keys always present:
\begin{description}
\item[type]
indicating a type of channel. Possible values are ``\textbf{file}'', ``\textbf{socket}'', ``\textbf{process}'' (result of [\textbf{open} ``\tipbar{}...'']), empty string (in case of channel that doesn't support this information), or any custom type, depending of refchan implementations. This is a mandatory key.
\end{description}

The remainder of the keys are optional and depend on the type.

For \textbf{file} channels, the dictionary shall include these:
\begin{description}
\item[path]
full, normalized path to the file, including the file name.
\item[new]
boolean value indicating whether file already existed while opening, or it was created.
\end{description}

For \textbf{socket} channels, the dictionary shall include these:
\begin{description}
\item[host]
peer hostname, or local hostname for listening socket. This is partially equivalent to getting the first value returned by [\textbf{chan configure} \textit{channelId} \textbf{-peername}] for connected sockets.
\item[port]
peer port, or listening port (for listening socket). This is partially equivalent to getting the third value returned by [\textbf{chan configure} \textit{channelId} \textbf{-peername}] for connected sockets.
\item[side]
one of the following: ``\textbf{client}'', ``\textbf{accepted}'', or ``\textbf{listening}''.
\end{description}

For \textbf{process} channels, the dictionary shall include these:
\begin{description}
\item[cmdline]
copy of the command passed to \textbf{open}.
\item[pid]
PID of a spawned process, as produced by \textbf{pid}.
\end{description}

Any key could be produced by other channel types, notably including reflected channels.

\subsection{The chaninfo Operation of Reflected Channel Implementations}

The \textbf{chaninfo} subcommand of a reflected channel implementation command returns a dict that is provided in response to a \textbf{chan info} request. If the dictionary does not include the mandatory \textbf{type} member, the reflected channel baseline implementation will add it and set it to \textbf{refchan}. It is an error to return a non-dictionary.

Since reflected channels are free to set the type to anything, they can simulate standard channels, like ``\textbf{file}'', as well as create completely new types.

If the operation is not supported, the baseline implementation will treat it the same as if the operation returned an empty dictionary.

\section{Internals}

Channel structure in Tcl core would require another API level indicating channels that have a function returning an ``info'' dict. All core channels are expected to migrate to this level, although it's possible to stay at current API version --- it will just cause the \textbf{type} in \textbf{chan info} dict to be the \textit{typeName} field of the channel's \textit{Tcl\_ChannelType} structure, with no additional keys in the dict.

\section{Examples}

This is a a pure Tcl implementation of file type channel, so it supports new information in \textbf{chan info}:
\begingroup\small\begin{verbatim}
oo::class create filechan {
    variable path fd created filemode
    constructor {fpath mode} {
        set filemode $mode
        set path $fpath
    }

    method initialize {ch mode} {
        set exists [file exists $path]
        set fd [open $path $filemode]
        set created [expr { [file exists $path] && !$exists}]
        return "initialize finalize watch read seek chaninfo"
    }
    method finalize {ch} {
        ::close $fd
        my destroy
    }
    method watch {ch events} {
        foreach event [list read write] method [list readable writable] {
            if {$event in $events} {
                fileevent $fd $method [list chan postevent $ch $event]
            }
        }
    }

    # Must be present on a readable channel
    method read {ch count} {
        ::read $fd $count
    }

    # This method is optional, but useful for the example below
    method seek {ch offset base} {
        ::seek $fd $offset $base
    }

    method chaninfo {ch} {
        dict create type file path $path new $created
    }
}

proc openfile {file mode} {
    # lets not bother of what modes should be passed to [chan create],
    # it's just an example...
    chan create [list read write] [filechan new $file $mode]
}

set fd [openfile "myfile.txt" r]
puts [chan info $fd]
close $fd
\end{verbatim}
\endgroup

\section{Reference Implementation}

\url{http://sqlitestudio.pl/tcl/patches/tip-411-chan_info.patch}

Patch made against 8.6.0 (just before final release).

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\end{document}
