All files / json-pack/src/nfs/v4/client Nfsv4TcpClient.ts

63.46% Statements 99/156
41.3% Branches 19/46
63.63% Functions 14/22
69.56% Lines 96/138

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 24725x   25x 25x 25x 25x             25x 25x                                 25x   279x 279x 279x                 279x 279x 279x 279x 279x             279x 279x 279x 279x 279x 279x 279x 279x 279x       758x 758x 758x                                                 279x 279x 279x         279x 279x 279x       757x 757x 757x 757x 757x 757x 757x     757x         757x 757x 757x       757x 757x 757x       757x   1x 1x 1x         756x 756x       756x                               254x 254x 254x 254x 254x 1x 1x   254x                           757x   757x     757x 757x 757x 757x 757x 757x       757x 757x 757x             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x       1x 1x         279x 279x 279x   279x 279x              
import * as net from 'node:net';
import type * as stream from 'node:stream';
import {Nfsv4Decoder} from '../Nfsv4Decoder';
import {Nfsv4FullEncoder} from '../Nfsv4FullEncoder';
import {RmRecordDecoder} from '../../../rm';
import {
  RpcAcceptedReplyMessage,
  type RpcMessage,
  RpcMessageDecoder,
  RpcOpaqueAuth,
  RpcRejectedReplyMessage,
} from '../../../rpc';
import {EMPTY_READER, Nfsv4Proc, Nfsv4Const} from '../constants';
import {Nfsv4CompoundRequest, type Nfsv4CompoundResponse, type Nfsv4Request} from '../messages';
import type {Nfsv4Client} from './types';
 
export interface Nfsv4TcpClientOpts {
  host?: string;
  port?: number;
  timeout?: number;
  debug?: boolean;
  logger?: Pick<typeof console, 'log' | 'error'>;
}
 
interface PendingRequest {
  resolve: (response: Nfsv4CompoundResponse) => void;
  reject: (error: Error) => void;
  timeout?: NodeJS.Timeout;
}
 
export class Nfsv4TcpClient implements Nfsv4Client {
  public static fromDuplex(duplex: stream.Duplex, opts: Nfsv4TcpClientOpts = {}): Nfsv4TcpClient {
    const client = new Nfsv4TcpClient(opts);
    client.setSocket(duplex);
    return client;
  }
 
  public readonly host: string;
  public readonly port: number;
  public readonly timeout: number;
  public debug: boolean;
  public logger: Pick<typeof console, 'log' | 'error'>;
 
  private socket: stream.Duplex | null = null;
  private connected = false;
  private connecting = false;
  private xid = 0;
  private pendingRequests = new Map<number, PendingRequest>();
  protected rmDecoder: RmRecordDecoder;
  protected rpcDecoder: RpcMessageDecoder;
  private readonly nfsDecoder: Nfsv4Decoder;
  private readonly nfsEncoder: Nfsv4FullEncoder;
 
  constructor(opts: Nfsv4TcpClientOpts = {}) {
    this.host = opts.host || '127.0.0.1';
    this.port = opts.port || 2049;
    this.timeout = opts.timeout || 30000;
    this.debug = !!opts.debug;
    this.logger = opts.logger || console;
    this.rmDecoder = new RmRecordDecoder();
    this.rpcDecoder = new RpcMessageDecoder();
    this.nfsDecoder = new Nfsv4Decoder();
    this.nfsEncoder = new Nfsv4FullEncoder();
  }
 
  private nextXid(): number {
    this.xid = (this.xid + 1) >>> 0;
    Iif (this.xid === 0) this.xid = 1;
    return this.xid;
  }
 
  public async connect(): Promise<void> {
    Iif (this.connected) return;
    Iif (this.connecting) throw new Error('Connection already in progress');
    return new Promise((resolve, reject) => {
      this.connecting = true;
      const onError = (err: Error) => {
        this.connecting = false;
        this.connected = false;
        Iif (this.debug) this.logger.error('Socket error:', err);
        reject(err);
      };
      const socket = net.connect({host: this.host, port: this.port}, () => {
        Iif (this.debug) this.logger.log(`Connected to NFSv4 server at ${this.host}:${this.port}`);
        socket.removeListener('error', onError);
        resolve();
        this.setSocket(socket);
      });
      socket.once('error', onError);
    });
  }
 
  protected setSocket(socket: stream.Duplex): void {
    socket.on('data', this.onData.bind(this));
    socket.on('close', this.onClose.bind(this));
    socket.on('error', (err: Error) => {
      this.connecting = false;
      this.connected = false;
      Iif (this.debug) this.logger.error('Socket error:', err);
    });
    this.connected = true;
    this.connecting = false;
    this.socket = socket;
  }
 
  private onData(data: Uint8Array): void {
    const {rmDecoder, rpcDecoder} = this;
    rmDecoder.push(data);
    let record = rmDecoder.readRecord();
    while (record) {
      if (record.size()) {
        const rpcMessage = rpcDecoder.decodeMessage(record);
        if (rpcMessage) this.onRpcMessage(rpcMessage);
        else IEif (this.debug) this.logger.error('Failed to decode RPC message');
      }
      record = rmDecoder.readRecord();
    }
  }
 
  private onRpcMessage(msg: RpcMessage): void {
    if (msg instanceof RpcAcceptedReplyMessage) {
      const pending = this.pendingRequests.get(msg.xid);
      Iif (!pending) {
        Iif (this.debug) this.logger.error(`No pending request for XID ${msg.xid}`);
        return;
      }
      this.pendingRequests.delete(msg.xid);
      if (pending.timeout) clearTimeout(pending.timeout);
      Iif (msg.stat !== 0) {
        pending.reject(new Error(`RPC accepted reply error: stat=${msg.stat}`));
        return;
      }
      if (!msg.results) {
        // NULL procedure has no results, check if resolve expects no arguments
        if (pending.resolve.length === 0) {
          (pending.resolve as any)();
          return;
        }
        pending.reject(new Error('No results in accepted reply'));
        return;
      }
      const response = this.nfsDecoder.decodeCompoundResponse(msg.results);
      Iif (!response) {
        pending.reject(new Error('Failed to decode COMPOUND response'));
        return;
      }
      pending.resolve(response);
    } else Eif (msg instanceof RpcRejectedReplyMessage) {
      const pending = this.pendingRequests.get(msg.xid);
      Iif (!pending) {
        Iif (this.debug) this.logger.error(`No pending request for XID ${msg.xid}`);
        return;
      }
      this.pendingRequests.delete(msg.xid);
      Iif (pending.timeout) clearTimeout(pending.timeout);
      pending.reject(new Error(`RPC rejected reply: stat=${msg.stat}`));
    } else {
      Iif (this.debug) this.logger.error('Unexpected RPC message type:', msg);
    }
  }
 
  private onClose(): void {
    this.connected = false;
    this.connecting = false;
    Iif (this.debug) this.logger.log('Connection closed');
    const error = new Error('Connection closed');
    this.pendingRequests.forEach((pending, xid) => {
      if (pending.timeout) clearTimeout(pending.timeout);
      pending.reject(error);
    });
    this.pendingRequests.clear();
  }
 
  public async compound(request: Nfsv4CompoundRequest): Promise<Nfsv4CompoundResponse>;
  public async compound(
    operations: Nfsv4Request[],
    tag?: string,
    minorversion?: number,
  ): Promise<Nfsv4CompoundResponse>;
  public async compound(
    requestOrOps: Nfsv4CompoundRequest | Nfsv4Request[],
    tag: string = '',
    minorversion: number = 0,
  ): Promise<Nfsv4CompoundResponse> {
    Iif (!this.connected) throw new Error('Not connected');
    const request =
      requestOrOps instanceof Nfsv4CompoundRequest
        ? requestOrOps
        : new Nfsv4CompoundRequest(tag, minorversion, requestOrOps);
    const xid = this.nextXid();
    const cred = new RpcOpaqueAuth(0, EMPTY_READER);
    const verf = new RpcOpaqueAuth(0, EMPTY_READER);
    const encoded = this.nfsEncoder.encodeCall(xid, Nfsv4Proc.COMPOUND, cred, verf, request);
    return new Promise((resolve, reject) => {
      const timeout = setTimeout(() => {
        this.pendingRequests.delete(xid);
        reject(new Error(`Request timeout (XID ${xid})`));
      }, this.timeout);
      this.pendingRequests.set(xid, {resolve, reject, timeout});
      this.socket!.write(encoded);
      Iif (this.debug) {
        this.logger.log(`Sent COMPOUND request (XID ${xid}): ${request.argarray.length} operations`);
      }
    });
  }
 
  public async null(): Promise<void> {
    Iif (!this.connected) throw new Error('Not connected');
    const xid = this.nextXid();
    const cred = new RpcOpaqueAuth(0, EMPTY_READER);
    const verf = new RpcOpaqueAuth(0, EMPTY_READER);
    const writer = this.nfsEncoder.writer;
    const rmEncoder = this.nfsEncoder.rmEncoder;
    const rpcEncoder = this.nfsEncoder.rpcEncoder;
    const state = rmEncoder.startRecord();
    rpcEncoder.writeCall(xid, Nfsv4Const.PROGRAM, Nfsv4Const.VERSION, Nfsv4Proc.NULL, cred, verf);
    rmEncoder.endRecord(state);
    const encoded = writer.flush();
    return new Promise((resolve, reject) => {
      const timeout = setTimeout(() => {
        this.pendingRequests.delete(xid);
        reject(new Error(`NULL request timeout (XID ${xid})`));
      }, this.timeout);
      this.pendingRequests.set(xid, {
        resolve: () => resolve(),
        reject,
        timeout,
      } as any);
      this.socket!.write(encoded);
      Iif (this.debug) this.logger.log(`Sent NULL request (XID ${xid})`);
    });
  }
 
  public close(): void {
    if (this.socket) {
      this.socket.end();
      this.socket = null;
    }
    this.connected = false;
    this.connecting = false;
  }
 
  public isConnected(): boolean {
    return this.connected;
  }
}