@effect-vfs/nfs 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,13 +5,14 @@ import * as Duration from "effect/Duration";
5
5
  import * as Effect from "effect/Effect";
6
6
  import * as Option from "effect/Option";
7
7
  import * as Predicate from "effect/Predicate";
8
+ import * as Result from "effect/Result";
8
9
  import * as Schedule from "effect/Schedule";
9
10
  import * as Schema from "effect/Schema";
10
11
  import * as Semaphore from "effect/Semaphore";
11
12
  import { ExportCapacityError, InvalidNameError, validateName } from "./export.js";
12
13
  import { lockRange, MAX_OFFSET, overlaps } from "./lockRanges.js";
13
14
  import { RpcPolicyDenied } from "./rpc.js";
14
- import { Reader, Writer, XdrDecodeError } from "./xdr.js";
15
+ import { make as xdr, XdrCodec, XdrDecodeError, XdrEncodeError } from "./xdr.js";
15
16
  /** @internal */
16
17
  export const Status = {
17
18
  OK: 0,
@@ -341,10 +342,8 @@ const sameRequest = (left, right) => {
341
342
  return false;
342
343
  return true;
343
344
  };
344
- const bitmap = (reader, limit) => reader.array((item) => item.uint32(), limit);
345
- const writeBitmap = (writer, words) => {
346
- writer.array(words, (target, word) => target.uint32(word));
347
- };
345
+ const bitmap = (reader, limit) => reader.read(XdrCodec.array(XdrCodec.uint32, limit));
346
+ const writeBitmap = (writer, words) => writer.write(XdrCodec.array(XdrCodec.uint32), words);
348
347
  const attributesIn = (words) => {
349
348
  const result = [];
350
349
  for (let word = 0; word < words.length; word++) {
@@ -354,37 +353,49 @@ const attributesIn = (words) => {
354
353
  }
355
354
  return result;
356
355
  };
357
- const validateWritableAttributes = (words, bytes, limits) => {
356
+ const validateWritableAttributes = Effect.fnUntraced(function* (words, bytes, limits) {
358
357
  const attributes = attributesIn(words);
359
358
  if (attributes.some((attribute) => ![4, 33, 36, 37, 48, 54].includes(attribute)))
360
359
  return;
361
- const values = new Reader(bytes, limits);
360
+ const values = yield* xdr.openReader(bytes, limits);
362
361
  for (const attribute of attributes) {
363
362
  if (attribute === 4)
364
- values.uint64();
363
+ yield* values.read(XdrCodec.uint64);
365
364
  else if (attribute === 33)
366
- values.uint32();
365
+ yield* values.read(XdrCodec.uint32);
367
366
  else if (attribute === 36 || attribute === 37)
368
- values.string(limits.maxStringBytes);
367
+ yield* values.read(XdrCodec.string(limits.maxStringBytes));
369
368
  else if (attribute === 48 || attribute === 54) {
370
- const how = values.uint32();
369
+ const how = yield* values.read(XdrCodec.uint32);
371
370
  if (how === 1) {
372
- values.uint64();
373
- if (values.uint32() >= 1_000_000_000)
374
- throw new XdrDecodeError("Invalid attribute nanoseconds");
371
+ yield* values.read(XdrCodec.uint64);
372
+ if ((yield* values.read(XdrCodec.uint32)) >= 1_000_000_000) {
373
+ return yield* new XdrDecodeError({
374
+ reason: "range",
375
+ offset: yield* values.position,
376
+ path: ["attributes", attribute],
377
+ detail: "Invalid attribute nanoseconds"
378
+ });
379
+ }
380
+ }
381
+ else if (how !== 0) {
382
+ return yield* new XdrDecodeError({
383
+ reason: "discriminant",
384
+ offset: yield* values.position,
385
+ path: ["attributes", attribute],
386
+ detail: "Invalid set-time discriminant"
387
+ });
375
388
  }
376
- else if (how !== 0)
377
- throw new XdrDecodeError("Invalid set-time discriminant");
378
389
  }
379
390
  }
380
- values.finish();
381
- };
382
- const readAttributes = (reader, limits) => {
383
- const words = bitmap(reader, limits.maxBitmapWords);
384
- const values = reader.opaque(limits.maxOpaqueBytes);
385
- validateWritableAttributes(words, values, limits);
391
+ yield* values.finish;
392
+ });
393
+ const readAttributes = Effect.fnUntraced(function* (reader, limits) {
394
+ const words = yield* bitmap(reader, limits.maxBitmapWords);
395
+ const values = yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
396
+ yield* validateWritableAttributes(words, values, limits);
386
397
  return { bitmap: words, values };
387
- };
398
+ });
388
399
  const isNumericOwner = Schema.is(Schema.String.check(Schema.isPattern(/^(0|[1-9][0-9]*)$/)));
389
400
  const creationAttributes = Effect.fnUntraced(function* (create, limits, existing) {
390
401
  const attributes = attributesIn(create.attrs.bitmap);
@@ -393,7 +404,7 @@ const creationAttributes = Effect.fnUntraced(function* (create, limits, existing
393
404
  if (!supportedAttrs && !(existing && create.mode === 0)) {
394
405
  return yield* Effect.fail(create.mode === 3 ? Status.INVAL : Status.ATTRNOTSUPP);
395
406
  }
396
- const reader = new Reader(create.attrs.values, limits);
407
+ const reader = yield* xdr.openReader(create.attrs.values, limits);
397
408
  let mode = create.mode === 2 ? 0o600 : undefined;
398
409
  let size;
399
410
  const owner = {};
@@ -407,9 +418,9 @@ const creationAttributes = Effect.fnUntraced(function* (create, limits, existing
407
418
  if (!supported.includes(attribute))
408
419
  break;
409
420
  if (attribute === 4)
410
- size = reader.uint64();
421
+ size = yield* reader.read(XdrCodec.uint64);
411
422
  else if (attribute === 33) {
412
- const value = reader.uint32();
423
+ const value = yield* reader.read(XdrCodec.uint32);
413
424
  if (!existing) {
414
425
  if (value > 0o7777)
415
426
  return yield* Effect.fail(Status.INVAL);
@@ -417,7 +428,7 @@ const creationAttributes = Effect.fnUntraced(function* (create, limits, existing
417
428
  }
418
429
  }
419
430
  else if (attribute === 36 || attribute === 37) {
420
- const value = reader.string(limits.maxStringBytes);
431
+ const value = yield* reader.read(XdrCodec.string(limits.maxStringBytes));
421
432
  if (existing)
422
433
  continue;
423
434
  if (!isNumericOwner(value) || Number(value) > 0xffff_ffff)
@@ -428,10 +439,11 @@ const creationAttributes = Effect.fnUntraced(function* (create, limits, existing
428
439
  owner.gid = Number(value);
429
440
  }
430
441
  else {
431
- const how = reader.uint32();
442
+ const how = yield* reader.read(XdrCodec.uint32);
432
443
  const time = how === 0 ? { kind: "now" } : {
433
444
  kind: "value",
434
- nanoseconds: BigInt.asIntN(64, reader.uint64()) * 1000000000n + BigInt(reader.uint32())
445
+ nanoseconds: BigInt.asIntN(64, yield* reader.read(XdrCodec.uint64)) * 1000000000n +
446
+ BigInt(yield* reader.read(XdrCodec.uint32))
435
447
  };
436
448
  if (attribute === 48)
437
449
  times.access = time;
@@ -440,13 +452,16 @@ const creationAttributes = Effect.fnUntraced(function* (create, limits, existing
440
452
  }
441
453
  }
442
454
  if (supportedAttrs)
443
- reader.finish();
455
+ yield* reader.finish;
444
456
  if (create.mode >= 2) {
445
457
  // RFC 8881 18.16.4 permits timestamp storage. Both verifier halves enter
446
458
  // the creation candidate so a crash cannot separate the file from its verifier.
447
- const verifier = new Reader(create.verifier, limits);
448
- times.access = { kind: "value", nanoseconds: BigInt(verifier.uint32()) * 1000000000n };
449
- times.modification = { kind: "value", nanoseconds: BigInt(verifier.uint32()) * 1000000000n };
459
+ const verifier = yield* xdr.openReader(create.verifier, limits);
460
+ times.access = { kind: "value", nanoseconds: BigInt(yield* verifier.read(XdrCodec.uint32)) * 1000000000n };
461
+ times.modification = {
462
+ kind: "value",
463
+ nanoseconds: BigInt(yield* verifier.read(XdrCodec.uint32)) * 1000000000n
464
+ };
450
465
  }
451
466
  const settings = { times };
452
467
  if (mode !== undefined) {
@@ -465,73 +480,94 @@ const setattrAttributes = Effect.fnUntraced(function* (attrs, limits, supportedA
465
480
  if (invalid !== undefined) {
466
481
  return yield* Effect.fail(supportedAttributes.includes(invalid) ? Status.INVAL : Status.ATTRNOTSUPP);
467
482
  }
468
- const reader = new Reader(attrs.values, limits);
483
+ const reader = yield* xdr.openReader(attrs.values, limits);
469
484
  const changes = [];
470
485
  for (const attribute of attributes) {
471
486
  if (attribute === 4)
472
- changes.push({ kind: "size", attribute, value: reader.uint64() });
487
+ changes.push({ kind: "size", attribute, value: yield* reader.read(XdrCodec.uint64) });
473
488
  else if (attribute === 33) {
474
- const value = reader.uint32();
489
+ const value = yield* reader.read(XdrCodec.uint32);
475
490
  if (value > 0o7777)
476
491
  return yield* Effect.fail(Status.INVAL);
477
492
  changes.push({ kind: "mode", attribute, value });
478
493
  }
479
494
  else if (attribute === 36 || attribute === 37) {
480
- const value = reader.string(limits.maxStringBytes);
495
+ const value = yield* reader.read(XdrCodec.string(limits.maxStringBytes));
481
496
  if (!isNumericOwner(value) || Number(value) > 0xffff_ffff)
482
497
  return yield* Effect.fail(Status.BADOWNER);
483
498
  changes.push({ kind: "owner", attribute, value: Number(value) });
484
499
  }
485
500
  else if (attribute === 48 || attribute === 54) {
486
- const how = reader.uint32();
501
+ const how = yield* reader.read(XdrCodec.uint32);
487
502
  const value = how === 0 ? { kind: "now" } : {
488
503
  kind: "value",
489
- nanoseconds: BigInt.asIntN(64, reader.uint64()) * 1000000000n + BigInt(reader.uint32())
504
+ nanoseconds: BigInt.asIntN(64, yield* reader.read(XdrCodec.uint64)) * 1000000000n +
505
+ BigInt(yield* reader.read(XdrCodec.uint32))
490
506
  };
491
507
  changes.push({ kind: "time", attribute, value });
492
508
  }
493
509
  }
494
- reader.finish();
510
+ yield* reader.finish;
495
511
  return changes;
496
512
  });
497
- const readStateOwner = (reader, limits) => {
498
- reader.uint64();
499
- return reader.opaque(limits.maxOwnerBytes);
500
- };
501
- const readChannelAttrs = (reader) => ({
502
- headerPadding: reader.uint32(),
503
- maxRequest: reader.uint32(),
504
- maxResponse: reader.uint32(),
505
- maxCachedResponse: reader.uint32(),
506
- maxOperations: reader.uint32(),
507
- maxRequests: reader.uint32(),
508
- rdmaIrd: reader.array((item) => item.uint32(), 1)
513
+ const readStateOwner = Effect.fnUntraced(function* (reader, limits) {
514
+ yield* reader.read(XdrCodec.uint64);
515
+ return yield* reader.read(XdrCodec.opaque(limits.maxOwnerBytes));
509
516
  });
510
- const readCallbackSecurity = (reader, limits) => {
511
- const flavor = reader.uint32();
517
+ const ChannelAttrsCodec = XdrCodec.struct({
518
+ headerPadding: XdrCodec.uint32,
519
+ maxRequest: XdrCodec.uint32,
520
+ maxResponse: XdrCodec.uint32,
521
+ maxCachedResponse: XdrCodec.uint32,
522
+ maxOperations: XdrCodec.uint32,
523
+ maxRequests: XdrCodec.uint32,
524
+ rdmaIrd: XdrCodec.array(XdrCodec.uint32, 1)
525
+ });
526
+ const readChannelAttrs = (reader) => reader.read(ChannelAttrsCodec);
527
+ const readCallbackSecurity = Effect.fnUntraced(function* (reader, limits) {
528
+ const flavor = yield* reader.read(XdrCodec.uint32);
512
529
  if (flavor === 0)
513
530
  return { flavor };
514
531
  if (flavor === 1) {
515
- const stamp = reader.uint32();
516
- const machineName = reader.string(limits.maxStringBytes);
517
- const uid = reader.uint32();
518
- const gid = reader.uint32();
519
- const groups = reader.array((item) => item.uint32(), limits.maxArrayElements);
520
- return {
521
- flavor,
522
- credential: new Writer().uint32(stamp).string(machineName).uint32(uid).uint32(gid)
523
- .array(groups, (item, group) => item.uint32(group))
524
- .bytes()
525
- };
532
+ const stamp = yield* reader.read(XdrCodec.uint32);
533
+ const machineName = yield* reader.read(XdrCodec.string(limits.maxStringBytes));
534
+ const uid = yield* reader.read(XdrCodec.uint32);
535
+ const gid = yield* reader.read(XdrCodec.uint32);
536
+ const groups = yield* reader.read(XdrCodec.array(XdrCodec.uint32, limits.maxArrayElements));
537
+ const credential = yield* xdr.encode({ stamp, machineName, uid, gid, groups }, XdrCodec.struct({
538
+ stamp: XdrCodec.uint32,
539
+ machineName: XdrCodec.string(),
540
+ uid: XdrCodec.uint32,
541
+ gid: XdrCodec.uint32,
542
+ groups: XdrCodec.array(XdrCodec.uint32)
543
+ }), limits, ByteSize.toNumberUnsafe(limits.maxRecordBytes));
544
+ return { flavor, credential };
526
545
  }
527
546
  if (flavor === 6) {
528
- reader.uint32();
529
- reader.opaque(limits.maxOpaqueBytes);
530
- reader.opaque(limits.maxOpaqueBytes);
547
+ yield* reader.read(XdrCodec.uint32);
548
+ yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
549
+ yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
531
550
  return { flavor };
532
551
  }
533
- throw new XdrDecodeError("Unsupported callback security flavor");
534
- };
552
+ return yield* new XdrDecodeError({
553
+ reason: "discriminant",
554
+ offset: yield* reader.position,
555
+ path: [],
556
+ detail: "Unsupported callback security flavor"
557
+ });
558
+ });
559
+ const readCallbackSecurityArray = Effect.fnUntraced(function* (reader, limits) {
560
+ const count = yield* reader.read(XdrCodec.uint32);
561
+ if (count > limits.maxArrayElements) {
562
+ return yield* new XdrDecodeError({
563
+ reason: "length-limit",
564
+ offset: yield* reader.position,
565
+ path: [],
566
+ detail: "XDR array exceeds its element limit"
567
+ });
568
+ }
569
+ return yield* Effect.forEach(Array.from({ length: count }), () => readCallbackSecurity(reader, limits));
570
+ });
535
571
  /**
536
572
  * Picks the credential a callback will carry. AUTH_NONE is preferred when the client offered it,
537
573
  * since it needs no identity; otherwise the client's own AUTH_SYS credential is used. A client
@@ -544,59 +580,73 @@ const readCallbackSecurity = (reader, limits) => {
544
580
  */
545
581
  const chooseCallbackSecurity = (offered) => offered.find((entry) => entry.flavor === AUTH_NONE) ??
546
582
  offered.find((entry) => entry.flavor === AUTH_SYS && (entry.credential?.length ?? 0) <= MAX_OPAQUE_AUTH_BYTES);
547
- const writeChannelAttrs = (writer, attrs) => {
548
- writer.uint32(attrs.headerPadding).uint32(attrs.maxRequest).uint32(attrs.maxResponse)
549
- .uint32(attrs.maxCachedResponse).uint32(attrs.maxOperations).uint32(attrs.maxRequests)
550
- .array(attrs.rdmaIrd, (item, value) => item.uint32(value));
551
- };
583
+ const writeChannelAttrs = (writer, attrs) => writer.write(ChannelAttrsCodec, attrs);
552
584
  /** state_protect_ops4: the operations a client wants enforced and allowed under the protection. */
553
- const readStateProtectOps = (reader, limits) => {
554
- bitmap(reader, limits.maxBitmapWords);
555
- bitmap(reader, limits.maxBitmapWords);
556
- };
557
- const readStateProtection = (reader, limits) => {
558
- const how = reader.uint32();
585
+ const readStateProtectOps = Effect.fnUntraced(function* (reader, limits) {
586
+ yield* bitmap(reader, limits.maxBitmapWords);
587
+ yield* bitmap(reader, limits.maxBitmapWords);
588
+ });
589
+ const readStateProtection = Effect.fnUntraced(function* (reader, limits) {
590
+ const how = yield* reader.read(XdrCodec.uint32);
559
591
  if (how === SP4_MACH_CRED) {
560
- readStateProtectOps(reader, limits);
592
+ yield* readStateProtectOps(reader, limits);
561
593
  }
562
594
  else if (how === SP4_SSV) {
563
595
  // ssv_sp_parms4: ops, hash and encryption algorithm lists, window, and GSS handle count.
564
- readStateProtectOps(reader, limits);
565
- reader.array((item) => item.opaque(limits.maxOpaqueBytes), limits.maxArrayElements);
566
- reader.array((item) => item.opaque(limits.maxOpaqueBytes), limits.maxArrayElements);
567
- reader.uint32();
568
- reader.uint32();
596
+ yield* readStateProtectOps(reader, limits);
597
+ yield* reader.read(XdrCodec.array(XdrCodec.opaque(limits.maxOpaqueBytes), limits.maxArrayElements));
598
+ yield* reader.read(XdrCodec.array(XdrCodec.opaque(limits.maxOpaqueBytes), limits.maxArrayElements));
599
+ yield* reader.read(XdrCodec.uint32);
600
+ yield* reader.read(XdrCodec.uint32);
569
601
  }
570
602
  else if (how !== SP4_NONE) {
571
- throw new XdrDecodeError("Invalid state protection discriminant");
603
+ return yield* new XdrDecodeError({
604
+ reason: "discriminant",
605
+ offset: yield* reader.position,
606
+ path: [],
607
+ detail: "Invalid state protection discriminant"
608
+ });
572
609
  }
573
610
  return how;
574
- };
575
- const readLockType = (reader) => {
576
- const lockType = reader.uint32();
577
- if (lockType < 1 || lockType > 4)
578
- throw new XdrDecodeError("Invalid lock type");
611
+ });
612
+ const readLockType = Effect.fnUntraced(function* (reader) {
613
+ const lockType = yield* reader.read(XdrCodec.uint32);
614
+ if (lockType < 1 || lockType > 4) {
615
+ return yield* new XdrDecodeError({
616
+ reason: "range",
617
+ offset: yield* reader.position,
618
+ path: [],
619
+ detail: "Invalid lock type"
620
+ });
621
+ }
579
622
  return lockType;
580
- };
581
- const decodeOperation = (code, reader, limits) => {
623
+ });
624
+ const decodeOperation = Effect.fnUntraced(function* (code, reader, limits) {
582
625
  switch (code) {
583
626
  case Operation.ACCESS:
584
- return { kind: "Access", code, value: reader.uint32() };
627
+ return { kind: "Access", code, value: (yield* reader.read(XdrCodec.uint32)) };
585
628
  case Operation.CLOSE:
586
- return { kind: "Close", code, value: { sequence: reader.uint32(), stateid: reader.fixedOpaque(16) } };
629
+ return {
630
+ kind: "Close",
631
+ code,
632
+ value: {
633
+ sequence: (yield* reader.read(XdrCodec.uint32)),
634
+ stateid: (yield* reader.read(XdrCodec.fixedOpaque(16)))
635
+ }
636
+ };
587
637
  case Operation.CREATE: {
588
- const kind = reader.uint32();
589
- const target = kind === 5 ? reader.string(limits.maxStringBytes) : undefined;
638
+ const kind = yield* reader.read(XdrCodec.uint32);
639
+ const target = kind === 5 ? (yield* reader.read(XdrCodec.string(limits.maxStringBytes))) : undefined;
590
640
  if (kind === 3 || kind === 4) {
591
- reader.uint32();
592
- reader.uint32();
641
+ yield* reader.read(XdrCodec.uint32);
642
+ yield* reader.read(XdrCodec.uint32);
593
643
  }
594
- const name = reader.opaque(limits.maxOpaqueBytes);
595
- const attrs = readAttributes(reader, limits);
644
+ const name = yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
645
+ const attrs = yield* readAttributes(reader, limits);
596
646
  return { kind: "Create", code, value: { kind, name, attrs, target } };
597
647
  }
598
648
  case Operation.GETATTR:
599
- return { kind: "Getattr", code, value: bitmap(reader, limits.maxBitmapWords) };
649
+ return { kind: "Getattr", code, value: (yield* bitmap(reader, limits.maxBitmapWords)) };
600
650
  case Operation.GETFH:
601
651
  return { kind: "Getfh", code, value: undefined };
602
652
  case Operation.LOOKUPP:
@@ -610,90 +660,113 @@ const decodeOperation = (code, reader, limits) => {
610
660
  case Operation.SAVEFH:
611
661
  return { kind: "Savefh", code, value: undefined };
612
662
  case Operation.LINK:
613
- return { kind: "Link", code, value: reader.opaque(limits.maxOpaqueBytes) };
663
+ return { kind: "Link", code, value: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))) };
614
664
  case Operation.LOOKUP:
615
- return { kind: "Lookup", code, value: reader.opaque(limits.maxOpaqueBytes) };
665
+ return { kind: "Lookup", code, value: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))) };
616
666
  case Operation.REMOVE:
617
- return { kind: "Remove", code, value: reader.opaque(limits.maxOpaqueBytes) };
667
+ return { kind: "Remove", code, value: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))) };
618
668
  case Operation.OPEN: {
619
- const sequence = reader.uint32();
620
- const access = reader.uint32();
621
- const deny = reader.uint32();
622
- const client = reader.uint64();
623
- const owner = reader.opaque(limits.maxOwnerBytes);
624
- const openHow = reader.uint32();
669
+ const sequence = yield* reader.read(XdrCodec.uint32);
670
+ const access = yield* reader.read(XdrCodec.uint32);
671
+ const deny = yield* reader.read(XdrCodec.uint32);
672
+ const client = yield* reader.read(XdrCodec.uint64);
673
+ const owner = yield* reader.read(XdrCodec.opaque(limits.maxOwnerBytes));
674
+ const openHow = yield* reader.read(XdrCodec.uint32);
625
675
  let create;
626
676
  if (openHow === 1) {
627
- const createMode = reader.uint32();
677
+ const createMode = yield* reader.read(XdrCodec.uint32);
628
678
  let verifier = empty;
629
679
  let attrs = { bitmap: [], values: empty };
630
680
  if (createMode === 0 || createMode === 1) {
631
- attrs = readAttributes(reader, limits);
681
+ attrs = yield* readAttributes(reader, limits);
632
682
  }
633
683
  else if (createMode === 2) {
634
- verifier = reader.fixedOpaque(8);
684
+ verifier = yield* reader.read(XdrCodec.fixedOpaque(8));
635
685
  }
636
686
  else if (createMode === 3) {
637
- verifier = reader.fixedOpaque(8);
638
- attrs = readAttributes(reader, limits);
687
+ verifier = yield* reader.read(XdrCodec.fixedOpaque(8));
688
+ attrs = yield* readAttributes(reader, limits);
639
689
  }
640
690
  else {
641
- throw new XdrDecodeError("Invalid OPEN create mode");
691
+ return yield* new XdrDecodeError({
692
+ reason: "discriminant",
693
+ offset: yield* reader.position,
694
+ path: [],
695
+ detail: "Invalid OPEN create mode"
696
+ });
642
697
  }
643
698
  create = { mode: createMode, verifier, attrs };
644
699
  }
645
700
  else if (openHow !== 0) {
646
- throw new XdrDecodeError("Invalid OPEN how discriminant");
701
+ return yield* new XdrDecodeError({
702
+ reason: "discriminant",
703
+ offset: yield* reader.position,
704
+ path: [],
705
+ detail: "Invalid OPEN how discriminant"
706
+ });
647
707
  }
648
- const claim = reader.uint32();
708
+ const claim = yield* reader.read(XdrCodec.uint32);
649
709
  let name = empty;
650
710
  if (claim === 0 || claim === 3)
651
- name = reader.opaque(limits.maxOpaqueBytes);
711
+ name = yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
652
712
  else if (claim === 1)
653
- reader.uint32();
713
+ yield* reader.read(XdrCodec.uint32);
654
714
  else if (claim === 2) {
655
- reader.fixedOpaque(16);
656
- name = reader.opaque(limits.maxOpaqueBytes);
715
+ yield* reader.read(XdrCodec.fixedOpaque(16));
716
+ name = yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
657
717
  }
658
718
  else if (claim === 5)
659
- reader.fixedOpaque(16);
660
- else if (claim !== 4 && claim !== 6)
661
- throw new XdrDecodeError("Invalid OPEN claim");
719
+ yield* reader.read(XdrCodec.fixedOpaque(16));
720
+ else if (claim !== 4 && claim !== 6) {
721
+ return yield* new XdrDecodeError({
722
+ reason: "discriminant",
723
+ offset: yield* reader.position,
724
+ path: [],
725
+ detail: "Invalid OPEN claim"
726
+ });
727
+ }
662
728
  return { kind: "Open", code, value: { sequence, access, deny, client, owner, openHow, create, claim, name } };
663
729
  }
664
730
  case Operation.PUTFH:
665
- return { kind: "Putfh", code, value: reader.opaque(limits.maxOpaqueBytes) };
731
+ return { kind: "Putfh", code, value: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))) };
666
732
  case Operation.READ:
667
733
  return {
668
734
  code,
669
735
  kind: "Read",
670
- value: { stateid: reader.fixedOpaque(16), offset: reader.uint64(), count: reader.uint32() }
736
+ value: {
737
+ stateid: (yield* reader.read(XdrCodec.fixedOpaque(16))),
738
+ offset: (yield* reader.read(XdrCodec.uint64)),
739
+ count: (yield* reader.read(XdrCodec.uint32))
740
+ }
671
741
  };
672
742
  case Operation.READDIR:
673
743
  return {
674
744
  code,
675
745
  kind: "Readdir",
676
746
  value: {
677
- cookie: reader.uint64(),
678
- verifier: reader.fixedOpaque(8),
679
- dircount: reader.uint32(),
680
- maxcount: reader.uint32(),
681
- attrs: bitmap(reader, limits.maxBitmapWords)
747
+ cookie: (yield* reader.read(XdrCodec.uint64)),
748
+ verifier: (yield* reader.read(XdrCodec.fixedOpaque(8))),
749
+ dircount: (yield* reader.read(XdrCodec.uint32)),
750
+ maxcount: (yield* reader.read(XdrCodec.uint32)),
751
+ attrs: (yield* bitmap(reader, limits.maxBitmapWords))
682
752
  }
683
753
  };
684
754
  case Operation.RENAME:
685
755
  return {
686
756
  code,
687
757
  kind: "Rename",
688
- value: { oldName: reader.opaque(limits.maxOpaqueBytes), newName: reader.opaque(limits.maxOpaqueBytes) }
758
+ value: {
759
+ oldName: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))),
760
+ newName: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes)))
761
+ }
689
762
  };
690
763
  case Operation.SETATTR:
691
764
  return {
692
765
  code,
693
766
  kind: "Setattr",
694
767
  value: {
695
- stateid: reader.fixedOpaque(16),
696
- attrs: readAttributes(reader, limits)
768
+ stateid: (yield* reader.read(XdrCodec.fixedOpaque(16))),
769
+ attrs: (yield* readAttributes(reader, limits))
697
770
  }
698
771
  };
699
772
  case Operation.WRITE:
@@ -701,34 +774,34 @@ const decodeOperation = (code, reader, limits) => {
701
774
  code,
702
775
  kind: "Write",
703
776
  value: {
704
- stateid: reader.fixedOpaque(16),
705
- offset: reader.uint64(),
706
- stable: reader.uint32(),
707
- data: reader.opaque(limits.maxWriteBytes)
777
+ stateid: (yield* reader.read(XdrCodec.fixedOpaque(16))),
778
+ offset: (yield* reader.read(XdrCodec.uint64)),
779
+ stable: (yield* reader.read(XdrCodec.uint32)),
780
+ data: (yield* reader.read(XdrCodec.opaque(limits.maxWriteBytes)))
708
781
  }
709
782
  };
710
783
  case Operation.EXCHANGE_ID: {
711
- const verifier = reader.fixedOpaque(8);
712
- const owner = reader.opaque(limits.maxOwnerBytes);
713
- const flags = reader.uint32();
714
- const protection = readStateProtection(reader, limits);
784
+ const verifier = yield* reader.read(XdrCodec.fixedOpaque(8));
785
+ const owner = yield* reader.read(XdrCodec.opaque(limits.maxOwnerBytes));
786
+ const flags = yield* reader.read(XdrCodec.uint32);
787
+ const protection = yield* readStateProtection(reader, limits);
715
788
  // eia_client_impl_id<1>: at most one implementation record (RFC 5662).
716
- reader.array((item) => {
717
- item.string(limits.maxStringBytes);
718
- item.string(limits.maxStringBytes);
719
- item.uint64();
720
- item.uint32();
721
- }, 1);
789
+ yield* reader.read(XdrCodec.array(XdrCodec.struct({
790
+ domain: XdrCodec.string(limits.maxStringBytes),
791
+ name: XdrCodec.string(limits.maxStringBytes),
792
+ seconds: XdrCodec.uint64,
793
+ nanoseconds: XdrCodec.uint32
794
+ }), 1));
722
795
  return { kind: "ExchangeId", code, value: { verifier, owner, flags, protection } };
723
796
  }
724
797
  case Operation.CREATE_SESSION: {
725
- const client = reader.uint64();
726
- const sequence = reader.uint32();
727
- const flags = reader.uint32();
728
- const fore = readChannelAttrs(reader);
729
- const back = readChannelAttrs(reader);
730
- const callbackProgram = reader.uint32();
731
- const flavors = reader.array((item) => readCallbackSecurity(item, limits), limits.maxArrayElements);
798
+ const client = yield* reader.read(XdrCodec.uint64);
799
+ const sequence = yield* reader.read(XdrCodec.uint32);
800
+ const flags = yield* reader.read(XdrCodec.uint32);
801
+ const fore = yield* readChannelAttrs(reader);
802
+ const back = yield* readChannelAttrs(reader);
803
+ const callbackProgram = yield* reader.read(XdrCodec.uint32);
804
+ const flavors = yield* readCallbackSecurityArray(reader, limits);
732
805
  return {
733
806
  kind: "CreateSession",
734
807
  code,
@@ -745,57 +818,61 @@ const decodeOperation = (code, reader, limits) => {
745
818
  };
746
819
  }
747
820
  case Operation.DESTROY_SESSION:
748
- return { kind: "DestroySession", code, value: reader.fixedOpaque(16) };
821
+ return { kind: "DestroySession", code, value: (yield* reader.read(XdrCodec.fixedOpaque(16))) };
749
822
  case Operation.SEQUENCE:
750
823
  return {
751
824
  code,
752
825
  kind: "Sequence",
753
826
  value: {
754
- session: reader.fixedOpaque(16),
755
- sequence: reader.uint32(),
756
- slot: reader.uint32(),
757
- highest: reader.uint32(),
758
- cache: reader.boolean()
827
+ session: (yield* reader.read(XdrCodec.fixedOpaque(16))),
828
+ sequence: (yield* reader.read(XdrCodec.uint32)),
829
+ slot: (yield* reader.read(XdrCodec.uint32)),
830
+ highest: (yield* reader.read(XdrCodec.uint32)),
831
+ cache: (yield* reader.read(XdrCodec.boolean))
759
832
  }
760
833
  };
761
834
  case Operation.DESTROY_CLIENTID:
762
- return { kind: "DestroyClient", code, value: reader.uint64() };
835
+ return { kind: "DestroyClient", code, value: (yield* reader.read(XdrCodec.uint64)) };
763
836
  case Operation.RECLAIM_COMPLETE:
764
- return { kind: "ReclaimComplete", code, value: reader.boolean() };
837
+ return { kind: "ReclaimComplete", code, value: (yield* reader.read(XdrCodec.boolean)) };
765
838
  case Operation.COMMIT:
766
- return { kind: "Commit", code, value: { offset: reader.uint64(), count: reader.uint32() } };
839
+ return {
840
+ kind: "Commit",
841
+ code,
842
+ value: { offset: (yield* reader.read(XdrCodec.uint64)), count: (yield* reader.read(XdrCodec.uint32)) }
843
+ };
767
844
  case Operation.LOCK: {
768
- const lockType = readLockType(reader);
769
- const reclaim = reader.boolean();
770
- const offset = reader.uint64();
771
- const length = reader.uint64();
845
+ const lockType = yield* readLockType(reader);
846
+ const reclaim = yield* reader.read(XdrCodec.boolean);
847
+ const offset = yield* reader.read(XdrCodec.uint64);
848
+ const length = yield* reader.read(XdrCodec.uint64);
772
849
  let locker;
773
- if (reader.boolean()) {
774
- reader.uint32();
775
- const stateid = reader.fixedOpaque(16);
776
- reader.uint32();
777
- locker = { kind: "new", stateid, owner: readStateOwner(reader, limits) };
850
+ if ((yield* reader.read(XdrCodec.boolean))) {
851
+ yield* reader.read(XdrCodec.uint32);
852
+ const stateid = yield* reader.read(XdrCodec.fixedOpaque(16));
853
+ yield* reader.read(XdrCodec.uint32);
854
+ locker = { kind: "new", stateid, owner: (yield* readStateOwner(reader, limits)) };
778
855
  }
779
856
  else {
780
- const stateid = reader.fixedOpaque(16);
781
- reader.uint32();
857
+ const stateid = yield* reader.read(XdrCodec.fixedOpaque(16));
858
+ yield* reader.read(XdrCodec.uint32);
782
859
  locker = { kind: "existing", stateid };
783
860
  }
784
861
  return { kind: "Lock", code, value: { lockType, reclaim, offset, length, locker } };
785
862
  }
786
863
  case Operation.LOCKT: {
787
- const lockType = readLockType(reader);
788
- const offset = reader.uint64();
789
- const length = reader.uint64();
790
- const owner = readStateOwner(reader, limits);
864
+ const lockType = yield* readLockType(reader);
865
+ const offset = yield* reader.read(XdrCodec.uint64);
866
+ const length = yield* reader.read(XdrCodec.uint64);
867
+ const owner = yield* readStateOwner(reader, limits);
791
868
  return { kind: "Lockt", code, value: { lockType, offset, length, owner } };
792
869
  }
793
870
  case Operation.LOCKU: {
794
- readLockType(reader);
795
- reader.uint32();
796
- const stateid = reader.fixedOpaque(16);
797
- const offset = reader.uint64();
798
- const length = reader.uint64();
871
+ yield* readLockType(reader);
872
+ yield* reader.read(XdrCodec.uint32);
873
+ const stateid = yield* reader.read(XdrCodec.fixedOpaque(16));
874
+ const offset = yield* reader.read(XdrCodec.uint64);
875
+ const length = yield* reader.read(XdrCodec.uint64);
799
876
  return { kind: "Locku", code, value: { stateid, offset, length } };
800
877
  }
801
878
  case Operation.NVERIFY:
@@ -803,35 +880,43 @@ const decodeOperation = (code, reader, limits) => {
803
880
  return {
804
881
  kind: "Verify",
805
882
  code,
806
- value: { bitmap: bitmap(reader, limits.maxBitmapWords), values: reader.opaque(limits.maxOpaqueBytes) }
883
+ value: {
884
+ bitmap: (yield* bitmap(reader, limits.maxBitmapWords)),
885
+ values: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes)))
886
+ }
807
887
  };
808
888
  case Operation.OPEN_DOWNGRADE:
809
889
  return {
810
890
  kind: "OpenDowngrade",
811
891
  code,
812
892
  value: {
813
- stateid: reader.fixedOpaque(16),
814
- sequence: reader.uint32(),
815
- access: reader.uint32(),
816
- deny: reader.uint32()
893
+ stateid: (yield* reader.read(XdrCodec.fixedOpaque(16))),
894
+ sequence: (yield* reader.read(XdrCodec.uint32)),
895
+ access: (yield* reader.read(XdrCodec.uint32)),
896
+ deny: (yield* reader.read(XdrCodec.uint32))
817
897
  }
818
898
  };
819
899
  case Operation.PUTPUBFH:
820
900
  return { kind: "Putpubfh", code, value: undefined };
821
901
  case Operation.SECINFO:
822
- return { kind: "Secinfo", code, value: reader.opaque(limits.maxOpaqueBytes) };
902
+ return { kind: "Secinfo", code, value: (yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes))) };
823
903
  case Operation.SECINFO_NO_NAME: {
824
- const style = reader.uint32();
904
+ const style = yield* reader.read(XdrCodec.uint32);
825
905
  if (style !== SECINFO_STYLE4_CURRENT_FH && style !== SECINFO_STYLE4_PARENT) {
826
- throw new XdrDecodeError("Invalid SECINFO_NO_NAME style");
906
+ return yield* new XdrDecodeError({
907
+ reason: "discriminant",
908
+ offset: yield* reader.position,
909
+ path: [],
910
+ detail: "Invalid SECINFO_NO_NAME style"
911
+ });
827
912
  }
828
913
  return { kind: "SecinfoNoName", code, value: style };
829
914
  }
830
915
  case Operation.FREE_STATEID:
831
- return { kind: "FreeStateid", code, value: reader.fixedOpaque(16) };
916
+ return { kind: "FreeStateid", code, value: (yield* reader.read(XdrCodec.fixedOpaque(16))) };
832
917
  case Operation.BACKCHANNEL_CTL: {
833
- const program = reader.uint32();
834
- const flavors = reader.array((item) => readCallbackSecurity(item, limits), limits.maxArrayElements);
918
+ const program = yield* reader.read(XdrCodec.uint32);
919
+ const flavors = yield* readCallbackSecurityArray(reader, limits);
835
920
  return {
836
921
  kind: "BackchannelCtl",
837
922
  code,
@@ -839,24 +924,29 @@ const decodeOperation = (code, reader, limits) => {
839
924
  };
840
925
  }
841
926
  case Operation.BIND_CONN_TO_SESSION: {
842
- const session = reader.fixedOpaque(16);
843
- const direction = reader.uint32();
927
+ const session = yield* reader.read(XdrCodec.fixedOpaque(16));
928
+ const direction = yield* reader.read(XdrCodec.uint32);
844
929
  // channel_dir_from_client4: FORE (1), BACK (2), FORE_OR_BOTH (3), or BACK_OR_BOTH (7).
845
930
  if (direction < CDFC4_FORE || (direction > CDFC4_FORE_OR_BOTH && direction !== CDFC4_BACK_OR_BOTH)) {
846
- throw new XdrDecodeError("Invalid channel direction");
931
+ return yield* new XdrDecodeError({
932
+ reason: "discriminant",
933
+ offset: yield* reader.position,
934
+ path: [],
935
+ detail: "Invalid channel direction"
936
+ });
847
937
  }
848
- reader.boolean();
938
+ yield* reader.read(XdrCodec.boolean);
849
939
  return { kind: "BindConnToSession", code, value: { session, direction } };
850
940
  }
851
941
  case Operation.SET_SSV:
852
- reader.opaque(limits.maxOpaqueBytes);
853
- reader.opaque(limits.maxOpaqueBytes);
942
+ yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
943
+ yield* reader.read(XdrCodec.opaque(limits.maxOpaqueBytes));
854
944
  return { kind: "SetSsv", code, value: undefined };
855
945
  case Operation.TEST_STATEID:
856
946
  return {
857
947
  kind: "TestStateid",
858
948
  code,
859
- value: reader.array((item) => item.fixedOpaque(16), limits.maxArrayElements)
949
+ value: yield* reader.read(XdrCodec.array(XdrCodec.fixedOpaque(16), limits.maxArrayElements))
860
950
  };
861
951
  default:
862
952
  if (mustNotImplementOperations.has(code) || unsupportedOptionalOperations.has(code)) {
@@ -864,22 +954,37 @@ const decodeOperation = (code, reader, limits) => {
864
954
  }
865
955
  return { kind: "Unknown", code, value: undefined };
866
956
  }
867
- };
868
- const parseCompound = (bytes, limits) => {
869
- if (byteLength(bytes.length) > limits.maxCompoundBytes)
870
- throw new XdrDecodeError("COMPOUND exceeds byte limit");
871
- const reader = new Reader(bytes, limits);
872
- const tag = reader.opaque(limits.maxStringBytes);
873
- const minor = reader.uint32();
874
- const count = reader.uint32();
957
+ });
958
+ const parseCompound = Effect.fnUntraced(function* (bytes, limits) {
959
+ if (byteLength(bytes.length) > limits.maxCompoundBytes) {
960
+ return yield* new XdrDecodeError({
961
+ reason: "length-limit",
962
+ offset: 0,
963
+ path: [],
964
+ detail: "COMPOUND exceeds byte limit"
965
+ });
966
+ }
967
+ const reader = yield* xdr.openReader(bytes, limits);
968
+ const tag = yield* reader.read(XdrCodec.opaque(limits.maxStringBytes));
969
+ const minor = yield* reader.read(XdrCodec.uint32);
970
+ const count = yield* reader.read(XdrCodec.uint32);
875
971
  if (count > limits.maxOperations || count > limits.maxArrayElements) {
876
- throw new XdrDecodeError("COMPOUND operation count exceeds its limit");
972
+ return yield* new XdrDecodeError({
973
+ reason: "length-limit",
974
+ offset: yield* reader.position,
975
+ path: [],
976
+ detail: "COMPOUND operation count exceeds its limit"
977
+ });
877
978
  }
878
979
  const operations = [];
879
980
  let stopped = false;
880
981
  for (let index = 0; index < count; index++) {
881
- const code = reader.uint32();
882
- const operation = decodeOperation_(code);
982
+ const code = yield* reader.read(XdrCodec.uint32);
983
+ const decoded = yield* Effect.result(decodeOperation(code, reader, limits));
984
+ // SAFETY: decodeOperation returns a ParsedOperation on every successful branch.
985
+ const operation = Result.isFailure(decoded)
986
+ ? { kind: "Malformed", code, value: undefined }
987
+ : decoded.success;
883
988
  operations.push(operation);
884
989
  // The compound fails at an undecoded operation, so later bytes are never interpreted.
885
990
  if (operation.kind === "Unknown" || operation.kind === "NotSupported" || operation.kind === "Malformed") {
@@ -888,33 +993,22 @@ const parseCompound = (bytes, limits) => {
888
993
  }
889
994
  }
890
995
  if (!stopped)
891
- reader.finish();
996
+ yield* reader.finish;
892
997
  return { tag, minor, count, operations };
893
- /**
894
- * Section 15.1.1.1 defines NFS4ERR_BADXDR per operation: the operations before a
895
- * malformed one are still processed and reported.
896
- */
897
- function decodeOperation_(code) {
898
- try {
899
- return decodeOperation(code, reader, limits);
900
- }
901
- catch (error) {
902
- if (!(error instanceof XdrDecodeError))
903
- throw error;
904
- return { kind: "Malformed", code, value: undefined };
905
- }
906
- }
907
- };
908
- const encodeCompound = (tag, parts, overallStatus = parts.find((part) => part.status !== Status.OK)?.status ?? Status.OK) => {
909
- const status = overallStatus;
910
- const writer = new Writer().uint32(status).opaque(tag).uint32(parts.length);
998
+ });
999
+ const encodeCompound = (limits, tag, parts, overallStatus = parts.find((part) => part.status !== Status.OK)?.status ?? Status.OK) => Effect.gen(function* () {
1000
+ const writer = yield* xdr.openWriter(limits, ByteSize.toNumberUnsafe(limits.maxRecordBytes));
1001
+ yield* writer.write(XdrCodec.uint32, overallStatus);
1002
+ yield* writer.write(XdrCodec.opaque(limits.maxStringBytes), tag);
1003
+ yield* writer.write(XdrCodec.uint32, parts.length);
911
1004
  for (const part of parts) {
912
- writer.uint32(part.code).uint32(part.status);
1005
+ yield* writer.write(XdrCodec.uint32, part.code);
1006
+ yield* writer.write(XdrCodec.uint32, part.status);
913
1007
  if (part.body !== undefined)
914
- writer.fixedOpaque(part.body);
1008
+ yield* writer.appendEncoded(part.body);
915
1009
  }
916
- return writer.bytes();
917
- };
1010
+ return yield* writer.finish;
1011
+ });
918
1012
  const fsStatuses = {
919
1013
  NotFound: Status.NOENT,
920
1014
  AlreadyExists: Status.EXIST,
@@ -944,11 +1038,12 @@ const fsStatuses = {
944
1038
  };
945
1039
  /** @internal */
946
1040
  export const failureForFs = (error) => Object.hasOwn(fsStatuses, error.code) ? fsStatuses[error.code] : Status.SERVERFAULT;
947
- const encodeStatusBody = (build) => {
948
- const writer = new Writer();
949
- build(writer);
950
- return writer.bytes();
951
- };
1041
+ const field = (codec, value) => (writer) => writer.write(codec, value);
1042
+ const encodeStatusBody = (limits, fields) => Effect.gen(function* () {
1043
+ const writer = yield* xdr.openWriter(limits, ByteSize.toNumberUnsafe(limits.maxRecordBytes));
1044
+ yield* Effect.forEach(fields, (write) => write(writer), { discard: true });
1045
+ return yield* writer.finish;
1046
+ });
952
1047
  const baseSupportedAttributes = [
953
1048
  0,
954
1049
  1,
@@ -1028,39 +1123,37 @@ const isValidName = (name, maxNameBytes) => {
1028
1123
  return false;
1029
1124
  }
1030
1125
  };
1031
- const encodeTime = (writer, nanoseconds) => {
1032
- let seconds = nanoseconds / 1000000000n;
1033
- let nanos = nanoseconds % 1000000000n;
1034
- if (nanos < 0) {
1035
- seconds -= 1n;
1036
- nanos += 1000000000n;
1037
- }
1126
+ const encodeTime = (writer, nanoseconds) => Effect.gen(function* () {
1127
+ const remainder = nanoseconds % 1000000000n;
1128
+ const seconds = nanoseconds / 1000000000n - (remainder < 0n ? 1n : 0n);
1129
+ const nanos = remainder < 0n ? remainder + 1000000000n : remainder;
1038
1130
  if (seconds < -0x8000000000000000n || seconds > 0x7fffffffffffffffn)
1039
1131
  return false;
1040
- writer.uint64(BigInt.asUintN(64, seconds)).uint32(Number(nanos));
1132
+ yield* writer.write(XdrCodec.uint64, BigInt.asUintN(64, seconds));
1133
+ yield* writer.write(XdrCodec.uint32, Number(nanos));
1041
1134
  return true;
1042
- };
1043
- const encodeAttributeValues = (requested, observation, filehandle, export_, options, supportedAttributes, usage) => {
1135
+ });
1136
+ const encodeAttributeValues = (requested, observation, filehandle, export_, options, supportedAttributes, usage) => Effect.gen(function* () {
1044
1137
  if (requested.some((attribute) => !supportedAttributes.includes(attribute)))
1045
1138
  return undefined;
1046
- const values = new Writer();
1139
+ const values = yield* xdr.openWriter(options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
1047
1140
  const metadata = observation.value;
1048
1141
  for (const attribute of requested) {
1049
1142
  switch (attribute) {
1050
1143
  case 0:
1051
- writeBitmap(values, wordsFor(supportedAttributes));
1144
+ yield* writeBitmap(values, wordsFor(supportedAttributes));
1052
1145
  break;
1053
1146
  case 1:
1054
- values.uint32(metadata.kind === "file" ? 1 : metadata.kind === "directory" ? 2 : 5);
1147
+ yield* values.write(XdrCodec.uint32, metadata.kind === "file" ? 1 : metadata.kind === "directory" ? 2 : 5);
1055
1148
  break;
1056
1149
  case 2:
1057
- values.uint32(0x3);
1150
+ yield* values.write(XdrCodec.uint32, 0x3);
1058
1151
  break;
1059
1152
  case 3:
1060
- values.uint64(BigInt.asUintN(64, observation.revision));
1153
+ yield* values.write(XdrCodec.uint64, BigInt.asUintN(64, observation.revision));
1061
1154
  break;
1062
1155
  case 4:
1063
- values.uint64(metadata.size);
1156
+ yield* values.write(XdrCodec.uint64, metadata.size);
1064
1157
  break;
1065
1158
  case 5:
1066
1159
  case 6:
@@ -1068,107 +1161,112 @@ const encodeAttributeValues = (requested, observation, filehandle, export_, opti
1068
1161
  case 17:
1069
1162
  case 26:
1070
1163
  case 34:
1071
- values.boolean(true);
1164
+ yield* values.write(XdrCodec.boolean, true);
1072
1165
  break;
1073
1166
  case 7:
1074
1167
  case 16:
1075
- values.boolean(false);
1168
+ yield* values.write(XdrCodec.boolean, false);
1076
1169
  break;
1077
1170
  case 51:
1078
- values.uint64(0n).uint32(1);
1171
+ yield* values.write(XdrCodec.uint64, 0n);
1172
+ yield* values.write(XdrCodec.uint32, 1);
1079
1173
  break;
1080
1174
  case 76:
1081
- values.uint32(FSCHARSET_CAP4_ALLOWS_ONLY_UTF8);
1175
+ yield* values.write(XdrCodec.uint32, FSCHARSET_CAP4_ALLOWS_ONLY_UTF8);
1082
1176
  break;
1083
1177
  case 8:
1084
- values.uint64(export_.fsid[0]).uint64(export_.fsid[1]);
1178
+ yield* values.write(XdrCodec.uint64, export_.fsid[0]);
1179
+ yield* values.write(XdrCodec.uint64, export_.fsid[1]);
1085
1180
  break;
1086
1181
  case 10:
1087
- values.uint32(options.leaseDurationSeconds);
1182
+ yield* values.write(XdrCodec.uint32, options.leaseDurationSeconds);
1088
1183
  break;
1089
1184
  case 11:
1090
- values.uint32(Status.OK);
1185
+ yield* values.write(XdrCodec.uint32, Status.OK);
1091
1186
  break;
1092
1187
  case 19:
1093
- values.opaque(filehandle);
1188
+ yield* values.write(XdrCodec.opaque(), filehandle);
1094
1189
  break;
1095
1190
  case 20:
1096
1191
  case 55:
1097
- values.uint64(BigInt.asUintN(64, metadata.ino));
1192
+ yield* values.write(XdrCodec.uint64, BigInt.asUintN(64, metadata.ino));
1098
1193
  break;
1099
1194
  case 21:
1100
1195
  case 22:
1101
1196
  case 23: {
1102
1197
  const total = BigInt(export_.capacity.limits.maxEntries);
1103
- values.uint64(attribute === 23 ? total : total - BigInt(usage.entries));
1198
+ yield* values.write(XdrCodec.uint64, attribute === 23 ? total : total - BigInt(usage.entries));
1104
1199
  break;
1105
1200
  }
1106
1201
  case 27:
1107
- values.uint64(ByteSize.toBigInt(export_.capacity.limits.maxFileBytes));
1202
+ yield* values.write(XdrCodec.uint64, ByteSize.toBigInt(export_.capacity.limits.maxFileBytes));
1108
1203
  break;
1109
1204
  case 29:
1110
- values.uint32(ByteSize.toNumberUnsafe(options.limits.maxNameBytes));
1205
+ yield* values.write(XdrCodec.uint32, ByteSize.toNumberUnsafe(options.limits.maxNameBytes));
1111
1206
  break;
1112
1207
  case 30:
1113
- values.uint64(options.limits.maxReadBytes);
1208
+ yield* values.write(XdrCodec.uint64, options.limits.maxReadBytes);
1114
1209
  break;
1115
1210
  case 31:
1116
- values.uint64(options.limits.maxWriteBytes);
1211
+ yield* values.write(XdrCodec.uint64, options.limits.maxWriteBytes);
1117
1212
  break;
1118
1213
  case 33:
1119
- values.uint32(metadata.mode);
1214
+ yield* values.write(XdrCodec.uint32, metadata.mode);
1120
1215
  break;
1121
1216
  case 35:
1122
- values.uint32(metadata.nlink);
1217
+ yield* values.write(XdrCodec.uint32, metadata.nlink);
1123
1218
  break;
1124
1219
  case 36:
1125
- values.string(String(metadata.uid));
1220
+ yield* values.write(XdrCodec.string(), String(metadata.uid));
1126
1221
  break;
1127
1222
  case 37:
1128
- values.string(String(metadata.gid));
1223
+ yield* values.write(XdrCodec.string(), String(metadata.gid));
1129
1224
  break;
1130
1225
  case 42:
1131
1226
  case 43:
1132
1227
  case 44: {
1133
1228
  const total = ByteSize.toBigInt(export_.capacity.limits.maxBytes);
1134
- values.uint64(attribute === 44 ? total : total - usage.usedBytes);
1229
+ yield* values.write(XdrCodec.uint64, attribute === 44 ? total : total - usage.usedBytes);
1135
1230
  break;
1136
1231
  }
1137
1232
  case 45:
1138
- values.uint64(metadata.size);
1233
+ yield* values.write(XdrCodec.uint64, metadata.size);
1139
1234
  break;
1140
1235
  case 47:
1141
- if (!encodeTime(values, metadata.atimeNs))
1236
+ if (!(yield* encodeTime(values, metadata.atimeNs)))
1142
1237
  return undefined;
1143
1238
  break;
1144
1239
  case 52:
1145
- if (!encodeTime(values, metadata.ctimeNs))
1240
+ if (!(yield* encodeTime(values, metadata.ctimeNs)))
1146
1241
  return undefined;
1147
1242
  break;
1148
1243
  case 53:
1149
- if (!encodeTime(values, metadata.mtimeNs))
1244
+ if (!(yield* encodeTime(values, metadata.mtimeNs)))
1150
1245
  return undefined;
1151
1246
  break;
1152
1247
  case 75:
1153
- writeBitmap(values, options.writable ? wordsFor([4, 33, 36, 37]) : []);
1248
+ yield* writeBitmap(values, options.writable ? wordsFor([4, 33, 36, 37]) : []);
1154
1249
  break;
1155
1250
  }
1156
1251
  }
1157
- return values.bytes();
1158
- };
1159
- const encodeAttributes = (requested, observation, filehandle, export_, options, supportedAttributes, usage) => {
1160
- const values = encodeAttributeValues(requested, observation, filehandle, export_, options, supportedAttributes, usage);
1252
+ return yield* values.finish;
1253
+ });
1254
+ const encodeAttributes = (requested, observation, filehandle, export_, options, supportedAttributes, usage) => Effect.gen(function* () {
1255
+ const values = yield* encodeAttributeValues(requested, observation, filehandle, export_, options, supportedAttributes, usage);
1161
1256
  if (values === undefined)
1162
1257
  return undefined;
1163
- return encodeStatusBody((writer) => {
1164
- writeBitmap(writer, wordsFor(requested));
1165
- writer.opaque(values);
1166
- });
1167
- };
1258
+ return yield* encodeStatusBody(options.limits, [
1259
+ (writer) => writeBitmap(writer, wordsFor(requested)),
1260
+ field(XdrCodec.opaque(), values)
1261
+ ]);
1262
+ });
1168
1263
  /** Encodes a READDIR entry's attributes as only `rdattr_error` (RFC 8881 Section 18.23.3). */
1169
- const encodeReaddirError = (status) => encodeStatusBody((writer) => {
1170
- writeBitmap(writer, wordsFor([11]));
1171
- writer.opaque(new Writer().uint32(status).bytes());
1264
+ const encodeReaddirError = (status, limits) => Effect.gen(function* () {
1265
+ const error = yield* xdr.encode(status, XdrCodec.uint32, limits, ByteSize.toNumberUnsafe(limits.maxRecordBytes));
1266
+ return yield* encodeStatusBody(limits, [
1267
+ (writer) => writeBitmap(writer, wordsFor([11])),
1268
+ field(XdrCodec.opaque(), error)
1269
+ ]);
1172
1270
  });
1173
1271
  const supportedAccessMask = (kind) => {
1174
1272
  switch (kind) {
@@ -1223,30 +1321,40 @@ const grantedAccess = (supported, metadata, credentials) => {
1223
1321
  * The credential is the one the client authorized in csa_sec_parms (Section 18.36.3), never a
1224
1322
  * flavor it did not offer.
1225
1323
  */
1226
- const encodeCallbackCall = (xid, program, procedure, security, body) => {
1227
- const header = new Writer()
1228
- .uint32(xid).uint32(0).uint32(2)
1229
- .uint32(program).uint32(CALLBACK_RPC_VERSION).uint32(procedure)
1230
- .uint32(security.flavor).opaque(security.credential ?? empty)
1231
- .uint32(0).opaque(empty)
1232
- .bytes();
1233
- const message = new Uint8Array(header.length + body.length);
1234
- message.set(header);
1235
- message.set(body, header.length);
1236
- return message;
1237
- };
1324
+ const encodeCallbackCall = (xid, program, procedure, security, body, limits) => Effect.gen(function* () {
1325
+ const writer = yield* xdr.openWriter(limits, ByteSize.toNumberUnsafe(limits.maxRecordBytes));
1326
+ yield* writer.write(XdrCodec.uint32, xid);
1327
+ yield* writer.write(XdrCodec.uint32, 0);
1328
+ yield* writer.write(XdrCodec.uint32, 2);
1329
+ yield* writer.write(XdrCodec.uint32, program);
1330
+ yield* writer.write(XdrCodec.uint32, CALLBACK_RPC_VERSION);
1331
+ yield* writer.write(XdrCodec.uint32, procedure);
1332
+ yield* writer.write(XdrCodec.uint32, security.flavor);
1333
+ yield* writer.write(XdrCodec.opaque(ByteSize.bytes(MAX_OPAQUE_AUTH_BYTES)), security.credential ?? empty);
1334
+ yield* writer.write(XdrCodec.uint32, 0);
1335
+ yield* writer.write(XdrCodec.opaque(ByteSize.bytes(MAX_OPAQUE_AUTH_BYTES)), empty);
1336
+ yield* writer.appendEncoded(body);
1337
+ return yield* writer.finish;
1338
+ });
1238
1339
  /**
1239
1340
  * A CB_COMPOUND carrying CB_SEQUENCE alone. Section 20.9.3 requires CB_SEQUENCE to appear once and
1240
1341
  * first in every CB_COMPOUND, and erratum 6015 makes it REQUIRED rather than the OPTIONAL that
1241
1342
  * Table 17 prints. With no delegations or layouts to recall, this is the whole callback: it
1242
1343
  * exercises the backchannel and renews nothing else.
1243
1344
  */
1244
- const encodeCallbackSequence = (session, sequence, slot, highestSlot) => new Writer()
1245
- .string("probe").uint32(1).uint32(0).uint32(1)
1246
- .uint32(OP_CB_SEQUENCE)
1247
- .fixedOpaque(session).uint32(sequence).uint32(slot).uint32(highestSlot).boolean(false)
1248
- .array([], () => undefined)
1249
- .bytes();
1345
+ const encodeCallbackSequence = (session, sequence, slot, highestSlot, limits) => encodeStatusBody(limits, [
1346
+ field(XdrCodec.string(), "probe"),
1347
+ field(XdrCodec.uint32, 1),
1348
+ field(XdrCodec.uint32, 0),
1349
+ field(XdrCodec.uint32, 1),
1350
+ field(XdrCodec.uint32, OP_CB_SEQUENCE),
1351
+ field(XdrCodec.fixedOpaque(16), session),
1352
+ field(XdrCodec.uint32, sequence),
1353
+ field(XdrCodec.uint32, slot),
1354
+ field(XdrCodec.uint32, highestSlot),
1355
+ field(XdrCodec.boolean, false),
1356
+ field(XdrCodec.array(XdrCodec.uint32), [])
1357
+ ]);
1250
1358
  /**
1251
1359
  * Decides whether a callback reply actually says the client handled the callback. An RPC REPLY is
1252
1360
  * not success on its own: the client's RPC layer answers PROG_UNAVAIL for a program it does not
@@ -1254,49 +1362,42 @@ const encodeCallbackSequence = (session, sequence, slot, highestSlot) => new Wri
1254
1362
  * from a client with no working callback path. The CB_SEQUENCE result is checked too, because
1255
1363
  * Section 20.9.3 lets the client reject the slot or sequence it was given.
1256
1364
  */
1257
- const callbackAccepted = (reply, limits, session, slot, sequence) => {
1258
- try {
1259
- const reader = new Reader(reply, limits);
1260
- reader.uint32();
1261
- // RPC: REPLY, MSG_ACCEPTED, verifier, then SUCCESS.
1262
- if (reader.uint32() !== 1)
1263
- return false;
1264
- if (reader.uint32() !== 0)
1265
- return false;
1266
- reader.uint32();
1267
- reader.opaque(ByteSize.bytes(MAX_OPAQUE_AUTH_BYTES));
1268
- if (reader.uint32() !== 0)
1269
- return false;
1270
- // CB_COMPOUND: an all-OK status, then CB_SEQUENCE first (Section 20.9.3).
1271
- if (reader.uint32() !== Status.OK)
1272
- return false;
1273
- reader.string(limits.maxStringBytes);
1274
- // Exactly one result: this server sends a CB_SEQUENCE-only CB_COMPOUND, so anything else is
1275
- // not an answer to what it asked.
1276
- if (reader.uint32() !== 1)
1277
- return false;
1278
- if (reader.uint32() !== OP_CB_SEQUENCE)
1279
- return false;
1280
- if (reader.uint32() !== Status.OK)
1281
- return false;
1282
- // The client echoes what it was given; anything else means it answered a different callback.
1283
- const echoed = bytesKey(reader.fixedOpaque(16)) === bytesKey(session) &&
1284
- reader.uint32() === sequence &&
1285
- reader.uint32() === slot;
1286
- // csr_highest_slotid and csr_target_highest_slotid are mandatory, and nothing may follow the
1287
- // one result. Reading them out and finishing rejects a truncated or padded reply, which would
1288
- // otherwise pass as a working callback path.
1289
- reader.uint32();
1290
- reader.uint32();
1291
- reader.finish();
1292
- return echoed;
1293
- }
1294
- catch (error) {
1295
- if (error instanceof XdrDecodeError)
1296
- return false;
1297
- throw error;
1298
- }
1299
- };
1365
+ const callbackAccepted = (reply, limits, session, slot, sequence) => Effect.gen(function* () {
1366
+ const reader = yield* xdr.openReader(reply, limits);
1367
+ yield* reader.read(XdrCodec.uint32);
1368
+ // RPC: REPLY, MSG_ACCEPTED, verifier, then SUCCESS.
1369
+ if ((yield* reader.read(XdrCodec.uint32)) !== 1)
1370
+ return false;
1371
+ if ((yield* reader.read(XdrCodec.uint32)) !== 0)
1372
+ return false;
1373
+ yield* reader.read(XdrCodec.uint32);
1374
+ yield* reader.read(XdrCodec.opaque(ByteSize.bytes(MAX_OPAQUE_AUTH_BYTES)));
1375
+ if ((yield* reader.read(XdrCodec.uint32)) !== 0)
1376
+ return false;
1377
+ // CB_COMPOUND: an all-OK status, then CB_SEQUENCE first (Section 20.9.3).
1378
+ if ((yield* reader.read(XdrCodec.uint32)) !== Status.OK)
1379
+ return false;
1380
+ yield* reader.read(XdrCodec.string(limits.maxStringBytes));
1381
+ // Exactly one result: this server sends a CB_SEQUENCE-only CB_COMPOUND, so anything else is
1382
+ // not an answer to what it asked.
1383
+ if ((yield* reader.read(XdrCodec.uint32)) !== 1)
1384
+ return false;
1385
+ if ((yield* reader.read(XdrCodec.uint32)) !== OP_CB_SEQUENCE)
1386
+ return false;
1387
+ if ((yield* reader.read(XdrCodec.uint32)) !== Status.OK)
1388
+ return false;
1389
+ // The client echoes what it was given; anything else means it answered a different callback.
1390
+ const echoed = bytesKey(yield* reader.read(XdrCodec.fixedOpaque(16))) === bytesKey(session) &&
1391
+ (yield* reader.read(XdrCodec.uint32)) === sequence &&
1392
+ (yield* reader.read(XdrCodec.uint32)) === slot;
1393
+ // csr_highest_slotid and csr_target_highest_slotid are mandatory, and nothing may follow the
1394
+ // one result. Reading them out and finishing rejects a truncated or padded reply, which would
1395
+ // otherwise pass as a working callback path.
1396
+ yield* reader.read(XdrCodec.uint32);
1397
+ yield* reader.read(XdrCodec.uint32);
1398
+ yield* reader.finish;
1399
+ return echoed;
1400
+ }).pipe(Effect.catchTag("XdrDecodeError", () => Effect.succeed(false)));
1300
1401
  const makeOpaqueId = (generation, serial) => {
1301
1402
  const result = new Uint8Array(16);
1302
1403
  result.set(generation.subarray(0, 8), 0);
@@ -1447,6 +1548,7 @@ export const makeNfs4Handler = (export_, options) => {
1447
1548
  assertOptions(options);
1448
1549
  const storageGeneration = options.storageGeneration ?? options.generation;
1449
1550
  const supportedAttributes = supportedAttributesFor(export_);
1551
+ const encodeBody = (value, codec) => xdr.encode(value, codec, options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
1450
1552
  const sampleUsage = (requested) => requested.some((attribute) => capacityAttributes.has(attribute))
1451
1553
  ? export_.capacity.usage
1452
1554
  : Effect.succeed(null);
@@ -1479,17 +1581,13 @@ export const makeNfs4Handler = (export_, options) => {
1479
1581
  }
1480
1582
  return undefined;
1481
1583
  };
1482
- const deniedLock = (code, conflict) => ({
1483
- code,
1484
- status: Status.DENIED,
1485
- body: new Writer()
1486
- .uint64(conflict.entry.range.offset)
1487
- .uint64(conflict.entry.range.length)
1488
- .uint32(conflict.entry.type)
1489
- .uint64(conflict.state.client.id)
1490
- .opaque(conflict.state.owner)
1491
- .bytes()
1492
- });
1584
+ const deniedLock = (code, conflict) => Effect.map(encodeStatusBody(options.limits, [
1585
+ field(XdrCodec.uint64, conflict.entry.range.offset),
1586
+ field(XdrCodec.uint64, conflict.entry.range.length),
1587
+ field(XdrCodec.uint32, conflict.entry.type),
1588
+ field(XdrCodec.uint64, conflict.state.client.id),
1589
+ field(XdrCodec.opaque(), conflict.state.owner)
1590
+ ]), (body) => ({ code, status: Status.DENIED, body }));
1493
1591
  let replayBytes = ByteSize.bytes(0);
1494
1592
  const maxRpcRequestBytes = ByteSize.min(options.limits.maxRecordBytes, options.limits.maxCompoundBytes);
1495
1593
  const maxRpcResponseBytes = ByteSize.min(options.limits.maxRecordBytes, options.limits.maxCompoundBytes);
@@ -1526,9 +1624,9 @@ export const makeNfs4Handler = (export_, options) => {
1526
1624
  // ca_maxrequestsize bounds the whole RPC call the client will accept, not just its
1527
1625
  // CB_COMPOUND body, so the framed message is what gets measured. The xid does not change
1528
1626
  // the size, so any value serves for the measurement.
1529
- if (encodeCallbackCall(0, back.program, procedure, security, body).length > back.attrs.maxRequest) {
1627
+ const measured = yield* Effect.result(encodeCallbackCall(0, back.program, procedure, security, body, options.limits));
1628
+ if (Result.isFailure(measured) || measured.success.length > back.attrs.maxRequest)
1530
1629
  return false;
1531
- }
1532
1630
  // A carrier that fails outright must not burn the whole deadline when it is the only one,
1533
1631
  // so the race also ends as soon as every carrier has definitively failed.
1534
1632
  let failed = 0;
@@ -1546,7 +1644,12 @@ export const makeNfs4Handler = (export_, options) => {
1546
1644
  const reply = yield* Deferred.make();
1547
1645
  pendingCallbacks.set(xid, { carrier, reply });
1548
1646
  return yield* Effect.ensuring(Effect.gen(function* () {
1549
- const sent = yield* carrier.send(encodeCallbackCall(xid, back.program, procedure, security, body));
1647
+ const encoded = yield* Effect.result(encodeCallbackCall(xid, back.program, procedure, security, body, options.limits));
1648
+ if (Result.isFailure(encoded)) {
1649
+ yield* noteFailure;
1650
+ return yield* Effect.never;
1651
+ }
1652
+ const sent = yield* carrier.send(encoded.success);
1550
1653
  // A carrier that cannot be written to, or whose client rejects the callback, loses
1551
1654
  // the race instead of ending it. The outer deadline bounds the wait when every
1552
1655
  // carrier does so.
@@ -1555,7 +1658,7 @@ export const makeNfs4Handler = (export_, options) => {
1555
1658
  return yield* Effect.never;
1556
1659
  }
1557
1660
  const answered = yield* Deferred.await(reply);
1558
- if (accepted(answered))
1661
+ if (yield* accepted(answered))
1559
1662
  return true;
1560
1663
  yield* noteFailure;
1561
1664
  return yield* Effect.never;
@@ -1627,23 +1730,16 @@ export const makeNfs4Handler = (export_, options) => {
1627
1730
  }), handlerScope);
1628
1731
  yield* Effect.addFinalizer(() => Effect.forEach(opens.values(), (open) => open.close, { discard: true }));
1629
1732
  /** Reads only the leading SEQUENCE of a compound to find its session, tolerating later decode errors. */
1630
- const sequenceSessionOf = (bytes) => {
1631
- try {
1632
- const reader = new Reader(bytes, options.limits);
1633
- reader.opaque(options.limits.maxStringBytes);
1634
- const minor = reader.uint32();
1635
- const operationCount = reader.uint32();
1636
- if (minor !== 1 || reader.uint32() !== Operation.SEQUENCE)
1637
- return undefined;
1638
- const session = sessions.get(bytesKey(reader.fixedOpaque(16)));
1639
- return session === undefined ? undefined : { session, operationCount };
1640
- }
1641
- catch (error) {
1642
- if (error instanceof XdrDecodeError)
1643
- return undefined;
1644
- throw error;
1645
- }
1646
- };
1733
+ const sequenceSessionOf = (bytes) => Effect.gen(function* () {
1734
+ const reader = yield* xdr.openReader(bytes, options.limits);
1735
+ yield* reader.read(XdrCodec.opaque(options.limits.maxStringBytes));
1736
+ const minor = yield* reader.read(XdrCodec.uint32);
1737
+ const operationCount = yield* reader.read(XdrCodec.uint32);
1738
+ if (minor !== 1 || (yield* reader.read(XdrCodec.uint32)) !== Operation.SEQUENCE)
1739
+ return undefined;
1740
+ const session = sessions.get(bytesKey(yield* reader.read(XdrCodec.fixedOpaque(16))));
1741
+ return session === undefined ? undefined : { session, operationCount };
1742
+ }).pipe(Effect.catchTag("XdrDecodeError", () => Effect.as(Effect.void, undefined)));
1647
1743
  /**
1648
1744
  * `restore` reopens the compound's own interrupt window. The caller runs the whole compound
1649
1745
  * uninterruptibly so the replay-slot commit below cannot be torn in half, but an operation
@@ -1653,38 +1749,33 @@ export const makeNfs4Handler = (export_, options) => {
1653
1749
  * interrupt arriving between them rolls the slot back via `rollbackSequence` so nothing stays
1654
1750
  * charged for a reply that was never sent.
1655
1751
  */
1656
- const executeCompound = (call, export_, activeCaller, restore) => Effect.suspend(() => {
1657
- let parsed;
1658
- try {
1659
- parsed = parseCompound(call.arguments, options.limits);
1660
- }
1661
- catch (error) {
1662
- if (!(error instanceof XdrDecodeError))
1663
- throw error;
1664
- const tag = (() => {
1665
- try {
1666
- return new Reader(call.arguments, options.limits).opaque(options.limits.maxStringBytes);
1752
+ const executeCompound = (call, export_, activeCaller, restore) => Effect.flatMap(Effect.result(parseCompound(call.arguments, options.limits)), (parsedResult) => {
1753
+ if (Result.isFailure(parsedResult)) {
1754
+ return Effect.gen(function* () {
1755
+ const tagResult = yield* Effect.result(xdr.openReader(call.arguments, options.limits).pipe(Effect.flatMap((reader) => reader.read(XdrCodec.opaque(options.limits.maxStringBytes)))));
1756
+ const tag = Result.isFailure(tagResult) ? empty : tagResult.success;
1757
+ // Section 2.10.6.4: an oversized request is reported as such even when later
1758
+ // operations fail to decode.
1759
+ const oversized = yield* sequenceSessionOf(call.arguments);
1760
+ if (oversized !== undefined &&
1761
+ (call.requestBytes ?? call.arguments.length) > oversized.session.fore.maxRequest) {
1762
+ return yield* encodeCompound(options.limits, tag, [{
1763
+ code: Operation.SEQUENCE,
1764
+ status: Status.REQ_TOO_BIG
1765
+ }]);
1667
1766
  }
1668
- catch (tagError) {
1669
- if (!(tagError instanceof XdrDecodeError))
1670
- throw tagError;
1671
- return empty;
1767
+ if (oversized !== undefined && oversized.operationCount > oversized.session.fore.maxOperations) {
1768
+ return yield* encodeCompound(options.limits, tag, [{
1769
+ code: Operation.SEQUENCE,
1770
+ status: Status.TOO_MANY_OPS
1771
+ }]);
1672
1772
  }
1673
- })();
1674
- // Section 2.10.6.4: an oversized request is reported as such even when later
1675
- // operations fail to decode.
1676
- const oversized = sequenceSessionOf(call.arguments);
1677
- if (oversized !== undefined &&
1678
- (call.requestBytes ?? call.arguments.length) > oversized.session.fore.maxRequest) {
1679
- return Effect.succeed(encodeCompound(tag, [{ code: Operation.SEQUENCE, status: Status.REQ_TOO_BIG }]));
1680
- }
1681
- if (oversized !== undefined && oversized.operationCount > oversized.session.fore.maxOperations) {
1682
- return Effect.succeed(encodeCompound(tag, [{ code: Operation.SEQUENCE, status: Status.TOO_MANY_OPS }]));
1683
- }
1684
- return Effect.succeed(encodeCompound(tag, [], Status.BADXDR));
1773
+ return yield* encodeCompound(options.limits, tag, [], Status.BADXDR);
1774
+ });
1685
1775
  }
1776
+ const parsed = parsedResult.success;
1686
1777
  if (parsed.minor !== 1) {
1687
- return Effect.succeed(encodeCompound(parsed.tag, [], Status.MINOR_VERS_MISMATCH));
1778
+ return encodeCompound(options.limits, parsed.tag, [], Status.MINOR_VERS_MISMATCH);
1688
1779
  }
1689
1780
  const first = parsed.operations[0];
1690
1781
  const firstCode = first?.code;
@@ -1697,20 +1788,23 @@ export const makeNfs4Handler = (export_, options) => {
1697
1788
  // Sections 15.2 and 18.52: an illegal opcode answers as OP_ILLEGAL whether or not a
1698
1789
  // session exists, and arguments are decoded before any session check.
1699
1790
  if (first.kind === "Unknown") {
1700
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: Operation.ILLEGAL, status: Status.OP_ILLEGAL }]));
1791
+ return encodeCompound(options.limits, parsed.tag, [{
1792
+ code: Operation.ILLEGAL,
1793
+ status: Status.OP_ILLEGAL
1794
+ }]);
1701
1795
  }
1702
1796
  if (first.kind === "Malformed") {
1703
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: first.code, status: Status.BADXDR }]));
1797
+ return encodeCompound(options.limits, parsed.tag, [{ code: first.code, status: Status.BADXDR }]);
1704
1798
  }
1705
1799
  // Sections 18.34.3, 18.35.3, 18.36.3, 18.37.3, and 18.50.3: these MUST be the only operation.
1706
1800
  if (isBootstrap) {
1707
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: firstCode, status: Status.NOT_ONLY_OP }]));
1801
+ return encodeCompound(options.limits, parsed.tag, [{ code: firstCode, status: Status.NOT_ONLY_OP }]);
1708
1802
  }
1709
1803
  // Section 15.2 allows only NFS4ERR_NOTSUPP for the NFSv4.0 operations.
1710
1804
  if (mustNotImplementOperations.has(firstCode)) {
1711
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: firstCode, status: Status.NOTSUPP }]));
1805
+ return encodeCompound(options.limits, parsed.tag, [{ code: firstCode, status: Status.NOTSUPP }]);
1712
1806
  }
1713
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: firstCode, status: Status.OP_NOT_IN_SESSION }]));
1807
+ return encodeCompound(options.limits, parsed.tag, [{ code: firstCode, status: Status.OP_NOT_IN_SESSION }]);
1714
1808
  }
1715
1809
  if (first?.kind === "Sequence") {
1716
1810
  const value = first.value;
@@ -1722,7 +1816,10 @@ export const makeNfs4Handler = (export_, options) => {
1722
1816
  // so it happens before the retry is judged: even a false retry was transmitted here.
1723
1817
  associate(session, call.connection, CHANNEL_FORE);
1724
1818
  if (!sameRequest(slot.request, call.arguments) || slot.credentials !== credentialsKey(call.credentials)) {
1725
- return Effect.succeed(encodeCompound(parsed.tag, [{ code: Operation.SEQUENCE, status: Status.SEQ_FALSE_RETRY }]));
1819
+ return encodeCompound(options.limits, parsed.tag, [{
1820
+ code: Operation.SEQUENCE,
1821
+ status: Status.SEQ_FALSE_RETRY
1822
+ }]);
1726
1823
  }
1727
1824
  // A policy may remap the same wire credential between attempts. Never replay a
1728
1825
  // response computed under a caller that no longer has this request's authority.
@@ -1750,25 +1847,28 @@ export const makeNfs4Handler = (export_, options) => {
1750
1847
  rollbackSequence?.();
1751
1848
  }
1752
1849
  rollbackSequence = undefined;
1753
- return encodeCompound(parsed.tag, [{ code: Operation.SEQUENCE, status }]);
1850
+ return encodeCompound(options.limits, parsed.tag, [{ code: Operation.SEQUENCE, status }]);
1754
1851
  };
1755
1852
  for (let index = 0; index < parsed.operations.length; index++) {
1756
1853
  const operation = parsed.operations[index];
1757
1854
  let result;
1758
1855
  // Operations remain interruptible while waiting on the export. Their own commit
1759
1856
  // boundaries protect state changes; the consumed slot prevents rerunning them.
1760
- result = yield* restore(execute(operation));
1857
+ result = yield* restore(execute(operation)).pipe(Effect.catchTag("XdrEncodeError", (error) => Effect.succeed({
1858
+ code: operation.code,
1859
+ status: error.reason === "output-limit" ? Status.REP_TOO_BIG : Status.SERVERFAULT
1860
+ })));
1761
1861
  parts.push(result);
1762
1862
  if (index === 0 && mayChangeState && activeSlot !== undefined && result.status === Status.OK) {
1763
1863
  // Publish a consumed-slot marker before any later operation can commit. An
1764
1864
  // interrupted or failed operation can leave this marker instead of its full reply.
1765
1865
  const second = parsed.operations[1];
1766
- activeSlot.response = second === undefined
1767
- ? encodeCompound(parsed.tag, [result])
1768
- : encodeCompound(parsed.tag, [
1866
+ activeSlot.response = yield* (second === undefined
1867
+ ? encodeCompound(options.limits, parsed.tag, [result])
1868
+ : encodeCompound(options.limits, parsed.tag, [
1769
1869
  result,
1770
1870
  { code: second.code, status: Status.RETRY_UNCACHED_REP }
1771
- ]);
1871
+ ]));
1772
1872
  activeSlot.request = new Uint8Array(call.arguments);
1773
1873
  activeSlot.credentials = credentialsKey(call.credentials);
1774
1874
  if (activeCaller === undefined)
@@ -1780,20 +1880,27 @@ export const makeNfs4Handler = (export_, options) => {
1780
1880
  if (result.status !== Status.OK)
1781
1881
  break;
1782
1882
  }
1783
- const response = encodeCompound(parsed.tag, parts);
1883
+ const encodedResponse = yield* Effect.result(encodeCompound(options.limits, parsed.tag, parts));
1884
+ if (Result.isFailure(encodedResponse)) {
1885
+ if (encodedResponse.failure.reason === "output-limit") {
1886
+ return yield* rejectAfterExecution(Status.REP_TOO_BIG);
1887
+ }
1888
+ return yield* encodedResponse.failure;
1889
+ }
1890
+ const response = encodedResponse.success;
1784
1891
  const responseBytes = addBytes(byteLength(response.length), rpcReplyOverheadBytes);
1785
1892
  if (responseBytes > byteLength(activeSession?.fore.maxResponse ?? Number.MAX_SAFE_INTEGER)) {
1786
- return rejectAfterExecution(Status.REP_TOO_BIG);
1893
+ return yield* rejectAfterExecution(Status.REP_TOO_BIG);
1787
1894
  }
1788
1895
  if (shouldCache &&
1789
1896
  responseBytes > byteLength(activeSession?.fore.maxCachedResponse ?? Number.MAX_SAFE_INTEGER)) {
1790
- return rejectAfterExecution(Status.REP_TOO_BIG_TO_CACHE);
1897
+ return yield* rejectAfterExecution(Status.REP_TOO_BIG_TO_CACHE);
1791
1898
  }
1792
1899
  if (activeSlot !== undefined && shouldCache) {
1793
1900
  const retainedBytes = addBytes(byteLength(call.arguments.length), byteLength(response.length));
1794
1901
  if (retainedBytes > options.limits.maxReplayBytes ||
1795
1902
  addBytes(subtractBytes(replayBytes, activeSlot.retainedBytes ?? ByteSize.bytes(0)), retainedBytes) > options.limits.maxReplayBytes) {
1796
- return rejectAfterExecution(Status.REP_TOO_BIG_TO_CACHE);
1903
+ return yield* rejectAfterExecution(Status.REP_TOO_BIG_TO_CACHE);
1797
1904
  }
1798
1905
  replayBytes = subtractBytes(replayBytes, activeSlot.retainedBytes ?? ByteSize.bytes(0));
1799
1906
  activeSlot.response = new Uint8Array(response);
@@ -1809,15 +1916,15 @@ export const makeNfs4Handler = (export_, options) => {
1809
1916
  else if (activeSlot !== undefined) {
1810
1917
  const sequencePart = parts[0];
1811
1918
  const second = parsed.operations[1];
1812
- const replay = second === undefined
1813
- ? encodeCompound(parsed.tag, [sequencePart])
1814
- : encodeCompound(parsed.tag, [
1919
+ const replay = yield* (second === undefined
1920
+ ? encodeCompound(options.limits, parsed.tag, [sequencePart])
1921
+ : encodeCompound(options.limits, parsed.tag, [
1815
1922
  sequencePart,
1816
1923
  { code: second.code, status: Status.RETRY_UNCACHED_REP }
1817
- ]);
1924
+ ]));
1818
1925
  const retainedBytes = addBytes(byteLength(call.arguments.length), byteLength(replay.length));
1819
1926
  if (addBytes(subtractBytes(replayBytes, activeSlot.retainedBytes ?? ByteSize.bytes(0)), retainedBytes) > options.limits.maxReplayBytes) {
1820
- return rejectAfterExecution(Status.DELAY);
1927
+ return yield* rejectAfterExecution(Status.DELAY);
1821
1928
  }
1822
1929
  replayBytes = subtractBytes(replayBytes, activeSlot.retainedBytes ?? ByteSize.bytes(0));
1823
1930
  activeSlot.response = replay;
@@ -1836,13 +1943,18 @@ export const makeNfs4Handler = (export_, options) => {
1836
1943
  const noCurrent = () => ({ code: operation.code, status: Status.NOFILEHANDLE });
1837
1944
  const mapFs = (effect) => effect.pipe(Effect.mapError(failureForFs));
1838
1945
  const withCurrent = (f) => current === undefined ? Effect.fail(Status.NOFILEHANDLE) : f(current);
1839
- const statusResult = (effect, success = () => undefined) => effect.pipe(Effect.map((value) => {
1840
- const body = success(value);
1841
- return body === undefined
1946
+ const statusResult = (effect, success = () => undefined) => Effect.flatMap(Effect.result(effect), (outcome) => {
1947
+ if (Result.isFailure(outcome)) {
1948
+ return outcome.failure instanceof XdrEncodeError
1949
+ ? Effect.fail(outcome.failure)
1950
+ : Effect.succeed({ code: operation.code, status: outcome.failure });
1951
+ }
1952
+ const body = success(outcome.success);
1953
+ return Effect.map(Effect.isEffect(body) ? body : Effect.succeed(body), (encoded) => encoded === undefined
1842
1954
  ? { code: operation.code, status: Status.OK }
1843
- : { code: operation.code, status: Status.OK, body };
1844
- }), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
1845
- const requireAttributes = (attributes) => attributes === undefined ? Effect.fail(Status.SERVERFAULT) : Effect.succeed(attributes);
1955
+ : { code: operation.code, status: Status.OK, body: encoded });
1956
+ });
1957
+ const requireAttributes = (attributes) => Effect.filterOrFail(attributes, (value) => value !== undefined, () => Status.SERVERFAULT);
1846
1958
  /** Registers a filehandle only when the `filehandle` attribute (19) is requested. */
1847
1959
  const filehandleFor = (reference, requested) => requested.includes(19)
1848
1960
  ? export_.handleFor(reference).pipe(Effect.mapError(() => Status.SERVERFAULT))
@@ -1851,9 +1963,7 @@ export const makeNfs4Handler = (export_, options) => {
1851
1963
  * Requires a directory. Only operations whose Section 15.2 error list includes
1852
1964
  * NFS4ERR_SYMLINK may report a symbolic link as such; the others say NOTDIR.
1853
1965
  */
1854
- const requireDirectory = (reference, symlinkStatus) => mapFs(export_.observeMetadata(reference)).pipe(Effect.flatMap((observation) => observation.value.kind === "directory"
1855
- ? Effect.void
1856
- : Effect.fail(observation.value.kind === "symlink" ? symlinkStatus : Status.NOTDIR)));
1966
+ const requireDirectory = (reference, symlinkStatus) => mapFs(export_.observeMetadata(reference)).pipe(Effect.filterOrFail((observation) => observation.value.kind === "directory", (observation) => observation.value.kind === "symlink" ? symlinkStatus : Status.NOTDIR), Effect.asVoid);
1857
1967
  const parentOfDirectory = (reference, symlinkStatus) => requireDirectory(reference, symlinkStatus).pipe(Effect.flatMap(() => parentOf(reference)));
1858
1968
  /** Requires a regular file, naming the offending type as Sections 18.16.4 and 18.22.3 do. */
1859
1969
  const requireRegularFile = (reference) => mapFs(export_.observeMetadata(reference)).pipe(Effect.flatMap((observation) => {
@@ -1902,10 +2012,11 @@ export const makeNfs4Handler = (export_, options) => {
1902
2012
  },
1903
2013
  catch: (error) => error instanceof InvalidNameError ? nameStatus(error) : Status.SERVERFAULT
1904
2014
  });
1905
- const writeChangeInfo = (writer, change) => {
1906
- writer.boolean(true).uint64(BigInt.asUintN(64, change.before))
1907
- .uint64(BigInt.asUintN(64, change.after));
1908
- };
2015
+ const writeChangeInfo = (change) => (writer) => Effect.gen(function* () {
2016
+ yield* writer.write(XdrCodec.boolean, true);
2017
+ yield* writer.write(XdrCodec.uint64, BigInt.asUintN(64, change.before));
2018
+ yield* writer.write(XdrCodec.uint64, BigInt.asUintN(64, change.after));
2019
+ });
1909
2020
  switch (operation.kind) {
1910
2021
  case "ExchangeId": {
1911
2022
  const value = operation.value;
@@ -1954,6 +2065,7 @@ export const makeNfs4Handler = (export_, options) => {
1954
2065
  return { code: operation.code, status: Status.DELAY };
1955
2066
  }
1956
2067
  let previous;
2068
+ let revokeConfirmed = false;
1957
2069
  if (confirmedRecord !== undefined && confirmedRecord.principal !== principal) {
1958
2070
  // Case 3: owner collision with another principal. Live state protects the
1959
2071
  // confirmed record; otherwise it is replaced outright.
@@ -1962,8 +2074,7 @@ export const makeNfs4Handler = (export_, options) => {
1962
2074
  if (hasState && options.now() <= confirmedRecord.leaseExpiresAt) {
1963
2075
  return { code: operation.code, status: Status.CLID_INUSE };
1964
2076
  }
1965
- yield* revokeClient(confirmedRecord);
1966
- removeClientRecord(confirmedRecord);
2077
+ revokeConfirmed = true;
1967
2078
  }
1968
2079
  else if (confirmedRecord !== undefined) {
1969
2080
  // Case 5: client restart. The confirmed record survives until CREATE_SESSION.
@@ -1976,12 +2087,8 @@ export const makeNfs4Handler = (export_, options) => {
1976
2087
  }
1977
2088
  // Case 4: any unconfirmed record for this owner is replaced by a new client ID.
1978
2089
  const unconfirmed = clientsByOwner.get(owner);
1979
- if (unconfirmed !== undefined && !unconfirmed.confirmed) {
1980
- releaseCreateSessionReplay(unconfirmed);
1981
- clients.delete(unconfirmed.id);
1982
- }
1983
2090
  const created = {
1984
- id: clientSerial++,
2091
+ id: clientSerial,
1985
2092
  owner,
1986
2093
  verifier,
1987
2094
  principal,
@@ -1992,28 +2099,45 @@ export const makeNfs4Handler = (export_, options) => {
1992
2099
  confirmed: false,
1993
2100
  createSessionReplay: undefined
1994
2101
  };
2102
+ // A failed response encode must not consume a client ID, replace an owner,
2103
+ // or revoke a confirmed record the caller cannot identify afterward.
2104
+ const response = yield* exchangeIdResult(created);
2105
+ if (revokeConfirmed && confirmedRecord !== undefined) {
2106
+ yield* revokeClient(confirmedRecord);
2107
+ removeClientRecord(confirmedRecord);
2108
+ }
2109
+ if (unconfirmed !== undefined && !unconfirmed.confirmed) {
2110
+ releaseCreateSessionReplay(unconfirmed);
2111
+ clients.delete(unconfirmed.id);
2112
+ }
2113
+ clientSerial++;
1995
2114
  clients.set(created.id, created);
1996
2115
  clientsByOwner.set(owner, created);
1997
- return exchangeIdResult(created);
2116
+ return response;
1998
2117
  });
1999
2118
  }
2000
- return Effect.succeed(exchangeIdResult(client));
2119
+ return exchangeIdResult(client);
2001
2120
  function exchangeIdResult(client) {
2002
- const body = encodeStatusBody((writer) => {
2003
- const flags = EXCHGID4_FLAG_USE_NON_PNFS |
2004
- (client.confirmed ? EXCHGID4_FLAG_CONFIRMED_R : 0);
2005
- writer.uint64(client.id).uint32(client.sequence).uint32(flags >>> 0).uint32(0);
2006
- writer.uint64(export_.fsid[0]).opaque(options.generation).opaque(options.generation);
2007
- writer.array([], () => undefined);
2008
- });
2009
- return { code: operation.code, status: Status.OK, body };
2121
+ const flags = EXCHGID4_FLAG_USE_NON_PNFS |
2122
+ (client.confirmed ? EXCHGID4_FLAG_CONFIRMED_R : 0);
2123
+ return Effect.map(encodeStatusBody(options.limits, [
2124
+ field(XdrCodec.uint64, client.id),
2125
+ field(XdrCodec.uint32, client.sequence),
2126
+ field(XdrCodec.uint32, flags >>> 0),
2127
+ field(XdrCodec.uint32, 0),
2128
+ field(XdrCodec.uint64, export_.fsid[0]),
2129
+ field(XdrCodec.opaque(), options.generation),
2130
+ field(XdrCodec.opaque(), options.generation),
2131
+ field(XdrCodec.array(XdrCodec.uint32), [])
2132
+ ]), (body) => ({ code: operation.code, status: Status.OK, body }));
2010
2133
  }
2011
2134
  }
2012
2135
  case "CreateSession": {
2013
2136
  const value = operation.value;
2014
2137
  const client = clients.get(value.client);
2015
- if (client === undefined)
2138
+ if (client === undefined) {
2016
2139
  return Effect.succeed({ code: operation.code, status: Status.STALE_CLIENTID });
2140
+ }
2017
2141
  const replay = client.createSessionReplay;
2018
2142
  if (replay?.sequence === value.sequence) {
2019
2143
  // Section 18.36.4 phase 2: an equal csa_sequence identifies a retry, which may
@@ -2064,8 +2188,9 @@ export const makeNfs4Handler = (export_, options) => {
2064
2188
  if (!client.confirmed && client.principal !== principalKey(call.credentials)) {
2065
2189
  return { code: operation.code, status: Status.CLID_INUSE };
2066
2190
  }
2067
- if ((value.flags & ~CREATE_SESSION4_KNOWN_FLAGS) !== 0)
2191
+ if ((value.flags & ~CREATE_SESSION4_KNOWN_FLAGS) !== 0) {
2068
2192
  return complete(Status.INVAL);
2193
+ }
2069
2194
  // Section 18.36.3: a callback security entry naming an RPCSEC_GSS handle the
2070
2195
  // server did not issue is NFS4ERR_NOENT.
2071
2196
  if (value.gssCallback)
@@ -2094,11 +2219,13 @@ export const makeNfs4Handler = (export_, options) => {
2094
2219
  // internal limit on how many callbacks it issues, not a renegotiation.
2095
2220
  const back = { ...value.back, headerPadding: 0, rdmaIrd: [] };
2096
2221
  const agreedFlags = wantsBackChannel ? CREATE_SESSION4_FLAG_CONN_BACK_CHAN : 0;
2097
- const body = encodeStatusBody((writer) => {
2098
- writer.fixedOpaque(id).uint32(value.sequence).uint32(agreedFlags);
2099
- writeChannelAttrs(writer, fore);
2100
- writeChannelAttrs(writer, back);
2101
- });
2222
+ const body = yield* encodeStatusBody(options.limits, [
2223
+ field(XdrCodec.fixedOpaque(16), id),
2224
+ field(XdrCodec.uint32, value.sequence),
2225
+ field(XdrCodec.uint32, agreedFlags),
2226
+ (writer) => writeChannelAttrs(writer, fore),
2227
+ (writer) => writeChannelAttrs(writer, back)
2228
+ ]);
2102
2229
  // Section 18.36.3: a channel that can never carry a SEQUENCE compound in either
2103
2230
  // direction, or fewer than two operations, is too small to be used.
2104
2231
  if (fore.maxRequest < MIN_FORE_REQUEST_BYTES || fore.maxResponse < MIN_FORE_RESPONSE_BYTES ||
@@ -2270,20 +2397,22 @@ export const makeNfs4Handler = (export_, options) => {
2270
2397
  const statusFlags = session.back !== undefined && !session.back.healthy
2271
2398
  ? SEQ4_STATUS_CB_PATH_DOWN_SESSION
2272
2399
  : 0;
2273
- const body = encodeStatusBody((writer) => {
2274
- writer.fixedOpaque(session.id).uint32(value.sequence).uint32(value.slot)
2275
- .uint32(session.slots.length - 1).uint32(session.slots.length - 1).uint32(statusFlags);
2400
+ return Effect.flatMap(encodeStatusBody(options.limits, [
2401
+ field(XdrCodec.fixedOpaque(16), session.id),
2402
+ field(XdrCodec.uint32, value.sequence),
2403
+ field(XdrCodec.uint32, value.slot),
2404
+ field(XdrCodec.uint32, session.slots.length - 1),
2405
+ field(XdrCodec.uint32, session.slots.length - 1),
2406
+ field(XdrCodec.uint32, statusFlags)
2407
+ ]), (body) => {
2408
+ // Probe only after the SEQUENCE reply body has encoded successfully.
2409
+ const back = session.back;
2410
+ if (back === undefined || back.probed) {
2411
+ return Effect.succeed({ code: operation.code, status: Status.OK, body });
2412
+ }
2413
+ back.probed = true;
2414
+ return Effect.forkIn(probe(session), handlerScope).pipe(Effect.as({ code: operation.code, status: Status.OK, body }));
2276
2415
  });
2277
- // The callback path is probed once, on the first SEQUENCE rather than during
2278
- // CREATE_SESSION, because only then is the client known to hold the session id
2279
- // that CB_SEQUENCE carries. It is forked because the probe's own reply arrives on
2280
- // this connection, whose read loop is busy with this compound until it returns.
2281
- const back = session.back;
2282
- if (back === undefined || back.probed) {
2283
- return Effect.succeed({ code: operation.code, status: Status.OK, body });
2284
- }
2285
- back.probed = true;
2286
- return Effect.forkIn(probe(session), handlerScope).pipe(Effect.as({ code: operation.code, status: Status.OK, body }));
2287
2416
  }
2288
2417
  case "ReclaimComplete": {
2289
2418
  if (activeSession === undefined) {
@@ -2339,11 +2468,11 @@ export const makeNfs4Handler = (export_, options) => {
2339
2468
  : bound === CHANNEL_FORE
2340
2469
  ? CDFS4_FORE
2341
2470
  : CDFS4_BOTH;
2342
- return Effect.succeed({
2343
- code: operation.code,
2344
- status: Status.OK,
2345
- body: new Writer().fixedOpaque(session.id).uint32(answered).boolean(false).bytes()
2346
- });
2471
+ return Effect.map(encodeStatusBody(options.limits, [
2472
+ field(XdrCodec.fixedOpaque(16), session.id),
2473
+ field(XdrCodec.uint32, answered),
2474
+ field(XdrCodec.boolean, false)
2475
+ ]), (body) => ({ code: operation.code, status: Status.OK, body }));
2347
2476
  }
2348
2477
  case "BackchannelCtl": {
2349
2478
  // Section 18.33.3: an RPCSEC_GSS handle the server never issued is NFS4ERR_NOENT.
@@ -2442,11 +2571,7 @@ export const makeNfs4Handler = (export_, options) => {
2442
2571
  case "Getfh":
2443
2572
  if (current === undefined)
2444
2573
  return Effect.succeed(noCurrent());
2445
- return export_.handleFor(current).pipe(Effect.map((handle) => ({
2446
- code: operation.code,
2447
- status: Status.OK,
2448
- body: new Writer().opaque(handle).bytes()
2449
- })), Effect.orElseSucceed(() => ({ code: operation.code, status: Status.SERVERFAULT })));
2574
+ return export_.handleFor(current).pipe(Effect.mapError(() => Status.SERVERFAULT), Effect.flatMap((handle) => Effect.map(encodeBody(handle, XdrCodec.opaque()), (body) => ({ code: operation.code, status: Status.OK, body }))), Effect.catchIf((error) => Predicate.isNumber(error), (status) => Effect.succeed({ code: operation.code, status })));
2450
2575
  case "Savefh":
2451
2576
  if (current === undefined)
2452
2577
  return Effect.succeed(noCurrent());
@@ -2469,7 +2594,7 @@ export const makeNfs4Handler = (export_, options) => {
2469
2594
  // SECINFO consumes the current filehandle (RFC 8881 Section 18.29.3).
2470
2595
  return statusResult(withCurrent((reference) => export_.lookup(reference, operation.value).pipe(Effect.mapError(nameStatus))), () => {
2471
2596
  setCurrent(undefined);
2472
- return new Writer().array(options.securityFlavors ?? [AUTH_SYS, AUTH_NONE], (writer, flavor) => writer.uint32(flavor)).bytes();
2597
+ return xdr.encode(options.securityFlavors ?? [AUTH_SYS, AUTH_NONE], XdrCodec.array(XdrCodec.uint32), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
2473
2598
  });
2474
2599
  case "Lookupp":
2475
2600
  return statusResult(withCurrent((reference) => parentOfDirectory(reference, Status.SYMLINK)), (reference) => {
@@ -2483,7 +2608,7 @@ export const makeNfs4Handler = (export_, options) => {
2483
2608
  ? parentOfDirectory(reference, Status.NOTDIR)
2484
2609
  : Effect.succeed(reference)), () => {
2485
2610
  setCurrent(undefined);
2486
- return new Writer().array(options.securityFlavors ?? [AUTH_SYS, AUTH_NONE], (writer, flavor) => writer.uint32(flavor)).bytes();
2611
+ return xdr.encode(options.securityFlavors ?? [AUTH_SYS, AUTH_NONE], XdrCodec.array(XdrCodec.uint32), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
2487
2612
  });
2488
2613
  case "Getattr": {
2489
2614
  if (current === undefined) {
@@ -2528,9 +2653,14 @@ export const makeNfs4Handler = (export_, options) => {
2528
2653
  ? grantedAccess(supported, observation.value, call.credentials)
2529
2654
  : 0;
2530
2655
  if (activeCaller !== undefined) {
2656
+ const writeFlags = observation.value.kind === "directory"
2657
+ ? [ACCESS4_MODIFY, ACCESS4_EXTEND, ACCESS4_DELETE]
2658
+ : [ACCESS4_MODIFY, ACCESS4_EXTEND];
2659
+ const writeBits = observation.value.kind === "directory" ? 0o3 : 0o2;
2531
2660
  for (const [flag, bit] of [
2532
2661
  [ACCESS4_READ, 0o4],
2533
- [observation.value.kind === "directory" ? ACCESS4_LOOKUP : ACCESS4_EXECUTE, 0o1]
2662
+ [observation.value.kind === "directory" ? ACCESS4_LOOKUP : ACCESS4_EXECUTE, 0o1],
2663
+ ...(options.writable ? writeFlags.map((flag) => [flag, writeBits]) : [])
2534
2664
  ]) {
2535
2665
  if ((supported & flag) === 0)
2536
2666
  continue;
@@ -2542,18 +2672,21 @@ export const makeNfs4Handler = (export_, options) => {
2542
2672
  }
2543
2673
  }
2544
2674
  return { supported, granted };
2545
- }), ({ supported, granted }) => new Writer().uint32(supported).uint32(granted).bytes());
2675
+ }), ({ supported, granted }) => encodeStatusBody(options.limits, [
2676
+ field(XdrCodec.uint32, supported),
2677
+ field(XdrCodec.uint32, granted)
2678
+ ]));
2546
2679
  }
2547
2680
  case "Commit": {
2548
2681
  if (current === undefined)
2549
2682
  return Effect.succeed(noCurrent());
2550
2683
  // Every writable mutation is committed before publication. There is no unstable
2551
2684
  // range to flush, but a failed provider must not produce a success reply.
2552
- return statusResult(requireRegularFile(current), () => new Writer().fixedOpaque(writeVerifier).bytes());
2685
+ return statusResult(requireRegularFile(current), () => xdr.encode(writeVerifier, XdrCodec.fixedOpaque(8), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)));
2553
2686
  }
2554
2687
  case "Readlink":
2555
2688
  // Section 18.24.4: an object that is not a symbolic link is NFS4ERR_WRONG_TYPE.
2556
- return statusResult(withCurrent((reference) => mapFs(export_.observeMetadata(reference)).pipe(Effect.filterOrFail((observation) => observation.value.kind === "symlink", () => Status.WRONG_TYPE), Effect.andThen(mapFs(export_.readLink(reference))), Effect.filterOrFail((target) => byteLength(target.length) <= options.limits.maxStringBytes, () => Status.SERVERFAULT))), (target) => new Writer().opaque(target).bytes());
2689
+ return statusResult(withCurrent((reference) => mapFs(export_.observeMetadata(reference)).pipe(Effect.filterOrFail((observation) => observation.value.kind === "symlink", () => Status.WRONG_TYPE), Effect.andThen(mapFs(export_.readLink(reference))), Effect.filterOrFail((target) => byteLength(target.length) <= options.limits.maxStringBytes, () => Status.SERVERFAULT))), (target) => xdr.encode(target, XdrCodec.opaque(), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)));
2557
2690
  case "Readdir": {
2558
2691
  if (current === undefined)
2559
2692
  return Effect.succeed(noCurrent());
@@ -2574,43 +2707,64 @@ export const makeNfs4Handler = (export_, options) => {
2574
2707
  if (!Number.isSafeInteger(start) || start < 0 || start > observation.value.length) {
2575
2708
  return { code: operation.code, status: Status.BAD_COOKIE };
2576
2709
  }
2577
- const writer = new Writer().fixedOpaque(verifier);
2578
- let count = 0;
2579
- let directoryBytes = 0;
2580
- const responseLimit = Math.min(value.maxcount, ByteSize.toNumberUnsafe(options.limits.maxReaddirReplyBytes));
2710
+ const paddedTagBytes = parsed.tag.length + (4 - parsed.tag.length % 4) % 4;
2711
+ const envelopeBytes = 44 + paddedTagBytes +
2712
+ parts.reduce((bytes, part) => bytes + 8 + (part.body?.length ?? 0), 0);
2713
+ const responseLimit = Math.min(value.maxcount, ByteSize.toNumberUnsafe(options.limits.maxReaddirReplyBytes), Math.max(0, ByteSize.toNumberUnsafe(maxRpcResponseBytes) - envelopeBytes), Math.max(0, (activeSession?.fore.maxResponse ?? Number.MAX_SAFE_INTEGER) - envelopeBytes), shouldCache
2714
+ ? Math.max(0, (activeSession?.fore.maxCachedResponse ?? Number.MAX_SAFE_INTEGER) - envelopeBytes)
2715
+ : Number.MAX_SAFE_INTEGER);
2581
2716
  if (responseLimit < 16) {
2582
2717
  return { code: operation.code, status: Status.TOOSMALL };
2583
2718
  }
2719
+ const writer = yield* xdr.openWriter(options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
2720
+ yield* writer.write(XdrCodec.fixedOpaque(8), verifier);
2721
+ let count = 0;
2722
+ let directoryBytes = 0;
2584
2723
  for (let item = start; item < observation.value.length && count < options.limits.maxReaddirEntries; item++) {
2585
2724
  const entry = observation.value[item];
2586
2725
  if (!isValidName(entry.name, options.limits.maxNameBytes)) {
2587
2726
  return { code: operation.code, status: Status.INVAL };
2588
2727
  }
2589
2728
  const attrs = supportedRequested.length === 0
2590
- ? new Writer().uint32(0).uint32(0).bytes()
2729
+ ? yield* encodeStatusBody(options.limits, [
2730
+ field(XdrCodec.uint32, 0),
2731
+ field(XdrCodec.uint32, 0)
2732
+ ])
2591
2733
  : yield* filehandleFor(entry.reference, supportedRequested).pipe(Effect.flatMap((handle) => mapFs(export_.observeMetadata(entry.reference)).pipe(Effect.flatMap((metadata) => requireAttributes(encodeAttributes(supportedRequested, metadata, handle, export_, options, supportedAttributes, usage))))),
2592
- // With rdattr_error requested, a failing entry reports its own error
2593
- // instead of failing the whole READDIR (RFC 8881 Section 18.23.3).
2594
- Effect.catch((status) => supportedRequested.includes(11)
2595
- ? Effect.succeed(encodeReaddirError(status))
2596
- : Effect.fail(status)));
2597
- const encoded = new Writer().boolean(true).uint64(BigInt(item + 3)).opaque(entry.name)
2598
- .fixedOpaque(attrs).bytes();
2734
+ // With rdattr_error requested, a failing entry reports its own error.
2735
+ Effect.catch((error) => {
2736
+ if (error instanceof XdrEncodeError)
2737
+ return Effect.fail(error);
2738
+ if (supportedRequested.includes(11))
2739
+ return encodeReaddirError(error, options.limits);
2740
+ return Effect.fail(error);
2741
+ }));
2742
+ const encoded = yield* encodeStatusBody(options.limits, [
2743
+ field(XdrCodec.boolean, true),
2744
+ field(XdrCodec.uint64, BigInt(item + 3)),
2745
+ field(XdrCodec.opaque(), entry.name),
2746
+ (itemWriter) => itemWriter.appendEncoded(attrs)
2747
+ ]);
2599
2748
  const entryDirectoryBytes = 12 + entry.name.length + (4 - entry.name.length % 4) % 4;
2600
2749
  if ((value.dircount !== 0 && directoryBytes + entryDirectoryBytes > value.dircount) ||
2601
- writer.length + encoded.length + 8 > responseLimit) {
2750
+ (yield* writer.length) + encoded.length + 8 > responseLimit) {
2602
2751
  if (count === 0) {
2603
2752
  return { code: operation.code, status: Status.TOOSMALL };
2604
2753
  }
2605
2754
  break;
2606
2755
  }
2607
- writer.fixedOpaque(encoded);
2756
+ yield* writer.appendEncoded(encoded);
2608
2757
  directoryBytes += entryDirectoryBytes;
2609
2758
  count += 1;
2610
2759
  }
2611
- writer.boolean(false).boolean(start + count >= observation.value.length);
2612
- return { code: operation.code, status: Status.OK, body: writer.bytes() };
2613
- })), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
2760
+ yield* writer.write(XdrCodec.boolean, false);
2761
+ yield* writer.write(XdrCodec.boolean, start + count >= observation.value.length);
2762
+ return {
2763
+ code: operation.code,
2764
+ status: Status.OK,
2765
+ body: yield* writer.finish
2766
+ };
2767
+ })), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
2614
2768
  }
2615
2769
  case "Open": {
2616
2770
  if (activeSession === undefined) {
@@ -2663,7 +2817,7 @@ export const makeNfs4Handler = (export_, options) => {
2663
2817
  return yield* Effect.fail(Status.EXIST);
2664
2818
  // Existing-file creates ignore initial values; the attribute mask and
2665
2819
  // XDR structure still obey the selected create mode's restrictions.
2666
- const attrs = yield* creationAttributes(create, options.limits, observed !== undefined);
2820
+ const attrs = yield* creationAttributes(create, options.limits, observed !== undefined).pipe(Effect.mapError((error) => error instanceof XdrDecodeError ? Status.BADXDR : error));
2667
2821
  if (observed !== undefined) {
2668
2822
  if (create.mode >= 2) {
2669
2823
  const times = attrs.settings.times;
@@ -2688,7 +2842,8 @@ export const makeNfs4Handler = (export_, options) => {
2688
2842
  if (existing === undefined && opens.size >= options.limits.maxOpens) {
2689
2843
  return yield* Effect.fail(Status.DELAY);
2690
2844
  }
2691
- const truncate = create.mode === 0 && attrs.settings.initialSize === 0n && observed !== undefined;
2845
+ const truncate = create.mode === 0 && attrs.settings.initialSize === 0n &&
2846
+ observed !== undefined;
2692
2847
  if (truncate && !wantsWrite)
2693
2848
  return yield* Effect.fail(Status.INVAL);
2694
2849
  const opened = yield* restore(export_.openChild(directory, value.name, {
@@ -2748,8 +2903,8 @@ export const makeNfs4Handler = (export_, options) => {
2748
2903
  }
2749
2904
  current = opened.reference;
2750
2905
  const applied = opened.created ? attrs.attributes : truncate ? [4] : [];
2751
- return openResult(id, opened.directory.before, true, opened.directory.after, create.mode >= 2 ? [...applied, 47, 53] : applied);
2752
- })).pipe(Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
2906
+ return yield* openResult(id, opened.directory.before, true, opened.directory.after, create.mode >= 2 ? [...applied, 47, 53] : applied);
2907
+ })).pipe(Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
2753
2908
  }
2754
2909
  const target = value.claim === 4
2755
2910
  ? Effect.succeed({ revision: 0n, reference: directory })
@@ -2758,7 +2913,8 @@ export const makeNfs4Handler = (export_, options) => {
2758
2913
  // Write access is refused only once the target is known to be a regular file.
2759
2914
  Effect.tap(() => wantsWrite && !options.writable ? Effect.fail(Status.ROFS) : Effect.void), Effect.flatMap(({ revision, reference }) => Effect.uninterruptibleMask((restore) => Effect.suspend(() => {
2760
2915
  const owner = bytesKey(value.owner);
2761
- const existing = [...opens.values()].find((open) => open.client === activeSession.client && open.owner === owner && open.reference === reference);
2916
+ const existing = [...opens.values()].find((open) => open.client === activeSession.client && open.owner === owner &&
2917
+ open.reference === reference);
2762
2918
  // Section 9.7 checks every open, including this open-owner's own state.
2763
2919
  const denied = [...opens.values()].some((open) => open.reference === reference &&
2764
2920
  ((open.deny & accessMode) !== 0 || (value.deny & open.access) !== 0));
@@ -2788,7 +2944,7 @@ export const makeNfs4Handler = (export_, options) => {
2788
2944
  existing.writeFile = opened.handle;
2789
2945
  existing.close = opened.close.pipe(Effect.andThen(previousClose));
2790
2946
  transferred = true;
2791
- }), (opened) => opened === null || transferred ? Effect.void : opened.close)), Effect.map(() => {
2947
+ }), (opened) => opened === null || transferred ? Effect.void : opened.close)), Effect.flatMap(() => {
2792
2948
  existing.access = nextAccess;
2793
2949
  existing.deny |= value.deny;
2794
2950
  advanceStateId(existing);
@@ -2800,7 +2956,7 @@ export const makeNfs4Handler = (export_, options) => {
2800
2956
  return Effect.succeed({ code: operation.code, status: Status.DELAY });
2801
2957
  }
2802
2958
  const serial = openSerial++;
2803
- return restore(mapFs(export_.open(reference, accessMode === 3 ? "readWrite" : wantsWrite ? "write" : "read"))).pipe(Effect.map((opened) => {
2959
+ return restore(mapFs(export_.open(reference, accessMode === 3 ? "readWrite" : wantsWrite ? "write" : "read"))).pipe(Effect.flatMap((opened) => {
2804
2960
  const id = makeStateId(options.generation, serial, 1);
2805
2961
  opens.set(stateIdKey(id), {
2806
2962
  id,
@@ -2817,30 +2973,30 @@ export const makeNfs4Handler = (export_, options) => {
2817
2973
  current = reference;
2818
2974
  return openResult(id, revision, value.claim === 4);
2819
2975
  }));
2820
- }))), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
2976
+ }))), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
2821
2977
  function openResult(id, revision, atomic, after = revision, attributes = []) {
2822
- currentStateid = id;
2823
- const body = encodeStatusBody((writer) => {
2824
- writer.fixedOpaque(id).boolean(atomic)
2825
- .uint64(BigInt.asUintN(64, revision))
2826
- .uint64(BigInt.asUintN(64, after)).uint32(0);
2827
- writeBitmap(writer, wordsFor(attributes));
2828
- if (delegationWant === 0) {
2829
- writer.uint32(OPEN_DELEGATE_NONE);
2830
- }
2831
- else {
2832
- // Section 18.16.3: a want that is not satisfied MUST be answered with
2833
- // OPEN_DELEGATE_NONE_EXT and a reason. NOT_WANTED and CANCELLED carry no body,
2834
- // and NOT_SUPP_FTYPE is the honest reason for a server without delegations.
2835
- const why = delegationWant === OPEN4_SHARE_ACCESS_WANT_NO_DELEG
2978
+ const delegationFields = delegationWant === 0
2979
+ ? [field(XdrCodec.uint32, OPEN_DELEGATE_NONE)]
2980
+ : [
2981
+ field(XdrCodec.uint32, OPEN_DELEGATE_NONE_EXT),
2982
+ field(XdrCodec.uint32, delegationWant === OPEN4_SHARE_ACCESS_WANT_NO_DELEG
2836
2983
  ? WND4_NOT_WANTED
2837
2984
  : delegationWant === OPEN4_SHARE_ACCESS_WANT_CANCEL
2838
2985
  ? WND4_CANCELLED
2839
- : WND4_NOT_SUPP_FTYPE;
2840
- writer.uint32(OPEN_DELEGATE_NONE_EXT).uint32(why);
2841
- }
2986
+ : WND4_NOT_SUPP_FTYPE)
2987
+ ];
2988
+ return Effect.map(encodeStatusBody(options.limits, [
2989
+ field(XdrCodec.fixedOpaque(16), id),
2990
+ field(XdrCodec.boolean, atomic),
2991
+ field(XdrCodec.uint64, BigInt.asUintN(64, revision)),
2992
+ field(XdrCodec.uint64, BigInt.asUintN(64, after)),
2993
+ field(XdrCodec.uint32, 0),
2994
+ (writer) => writeBitmap(writer, wordsFor(attributes)),
2995
+ ...delegationFields
2996
+ ]), (body) => {
2997
+ currentStateid = id;
2998
+ return { code: operation.code, status: Status.OK, body };
2842
2999
  });
2843
- return { code: operation.code, status: Status.OK, body };
2844
3000
  }
2845
3001
  }
2846
3002
  case "Read": {
@@ -2860,7 +3016,7 @@ export const makeNfs4Handler = (export_, options) => {
2860
3016
  // reservation; the READ-bypass stateid (all ones) may ignore it.
2861
3017
  const denied = isAllZero(value.stateid) &&
2862
3018
  [...opens.values()].some((open) => open.reference === reference && (open.deny & OPEN4_SHARE_DENY_READ) !== 0);
2863
- return requireRegularFile(reference).pipe(Effect.andThen(denied ? Effect.fail(Status.LOCKED) : Effect.void), Effect.andThen(readPermission), Effect.andThen(Effect.acquireUseRelease(mapFs(export_.open(reference)), (opened) => readFrom(opened.handle), (opened) => opened.close)), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
3019
+ return requireRegularFile(reference).pipe(Effect.andThen(denied ? Effect.fail(Status.LOCKED) : Effect.void), Effect.andThen(readPermission), Effect.andThen(Effect.acquireUseRelease(mapFs(export_.open(reference)), (opened) => readFrom(opened.handle), (opened) => opened.close)), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
2864
3020
  }
2865
3021
  const effectiveStateid = isCurrentStateId(value.stateid) ? currentStateid : value.stateid;
2866
3022
  if (effectiveStateid === undefined) {
@@ -2889,30 +3045,33 @@ export const makeNfs4Handler = (export_, options) => {
2889
3045
  if (open.readFile === undefined) {
2890
3046
  return Effect.succeed({ code: operation.code, status: Status.SERVERFAULT });
2891
3047
  }
2892
- return readPermission.pipe(Effect.andThen(readFrom(open.readFile)), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
3048
+ return readPermission.pipe(Effect.andThen(readFrom(open.readFile)), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
2893
3049
  function readFrom(file) {
2894
- return file.pread(value.count, value.offset).pipe(Effect.flatMap((data) => file.stat.pipe(Effect.map((metadata) => ({ data, metadata })))), Effect.map(({ data, metadata }) => ({
2895
- code: operation.code,
2896
- status: Status.OK,
2897
- body: new Writer().boolean(value.offset + BigInt(data.length) >= metadata.size).opaque(data)
2898
- .bytes()
2899
- })), Effect.catch((error) => Effect.succeed({ code: operation.code, status: failureForFs(error) })));
3050
+ return file.pread(value.count, value.offset).pipe(Effect.flatMap((data) => file.stat.pipe(Effect.map((metadata) => ({ data, metadata })))), Effect.flatMap(({ data, metadata }) => Effect.map(encodeStatusBody(options.limits, [
3051
+ field(XdrCodec.boolean, value.offset + BigInt(data.length) >= metadata.size),
3052
+ field(XdrCodec.opaque(), data)
3053
+ ]), (body) => ({ code: operation.code, status: Status.OK, body }))), Effect.catchTag("FsError", (error) => Effect.succeed({ code: operation.code, status: failureForFs(error) })));
2900
3054
  }
2901
3055
  }
2902
3056
  case "OpenDowngrade": {
2903
- if (current === undefined)
3057
+ if (current === undefined) {
2904
3058
  return Effect.succeed(noCurrent());
3059
+ }
2905
3060
  const value = operation.value;
2906
3061
  // Section 16.2.3: the special current stateid refers to a preceding OPEN.
2907
3062
  const stateid = isCurrentStateId(value.stateid) ? currentStateid : value.stateid;
2908
- if (stateid === undefined)
3063
+ if (stateid === undefined) {
3064
+ // The special stateid has no earlier OPEN result to refer to.
2909
3065
  return Effect.succeed({ code: operation.code, status: Status.BAD_STATEID });
3066
+ }
2910
3067
  const open = opens.get(stateIdKey(stateid));
2911
- if (open === undefined)
3068
+ if (open === undefined) {
2912
3069
  return Effect.succeed({ code: operation.code, status: Status.BAD_STATEID });
3070
+ }
2913
3071
  const stateidStatus = checkOpenStateId(stateid, open);
2914
- if (stateidStatus !== Status.OK)
3072
+ if (stateidStatus !== Status.OK) {
2915
3073
  return Effect.succeed({ code: operation.code, status: stateidStatus });
3074
+ }
2916
3075
  // Section 18.18.3: delegation want bits are masked off, and the new modes must be
2917
3076
  // non-empty subsets of what is held.
2918
3077
  const access = value.access & ~OPEN4_SHARE_ACCESS_WANT_DELEG_MASK;
@@ -2923,11 +3082,7 @@ export const makeNfs4Handler = (export_, options) => {
2923
3082
  open.deny = value.deny;
2924
3083
  advanceStateId(open);
2925
3084
  currentStateid = open.id;
2926
- return Effect.succeed({
2927
- code: operation.code,
2928
- status: Status.OK,
2929
- body: new Writer().fixedOpaque(open.id).bytes()
2930
- });
3085
+ return Effect.map(xdr.encode(open.id, XdrCodec.fixedOpaque(16), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)), (body) => ({ code: operation.code, status: Status.OK, body }));
2931
3086
  }
2932
3087
  case "FreeStateid": {
2933
3088
  if (activeSession === undefined) {
@@ -2939,8 +3094,10 @@ export const makeNfs4Handler = (export_, options) => {
2939
3094
  const lock = lockStates.get(key);
2940
3095
  if (lock !== undefined && lock.client === activeSession.client) {
2941
3096
  const status = checkStateIdSequence(operation.value, lock);
2942
- if (status !== Status.OK)
3097
+ if (status !== Status.OK) {
3098
+ // A stale stateid cannot release the lock owner's state.
2943
3099
  return Effect.succeed({ code: operation.code, status });
3100
+ }
2944
3101
  if (lock.ranges.length !== 0) {
2945
3102
  return Effect.succeed({ code: operation.code, status: Status.LOCKS_HELD });
2946
3103
  }
@@ -2963,8 +3120,9 @@ export const makeNfs4Handler = (export_, options) => {
2963
3120
  const session = activeSession;
2964
3121
  // TEST_STATEID checks stateids alone; it does not involve the current filehandle.
2965
3122
  const results = operation.value.map((stateid) => {
2966
- if (isSpecialStateId(stateid))
3123
+ if (isSpecialStateId(stateid)) {
2967
3124
  return Status.BAD_STATEID;
3125
+ }
2968
3126
  const open = opens.get(stateIdKey(stateid));
2969
3127
  if (open === undefined) {
2970
3128
  const lock = lockStates.get(stateIdKey(stateid));
@@ -2972,48 +3130,53 @@ export const makeNfs4Handler = (export_, options) => {
2972
3130
  ? Status.BAD_STATEID
2973
3131
  : checkStateIdSequence(stateid, lock);
2974
3132
  }
2975
- if (open.client !== session.client)
3133
+ if (open.client !== session.client) {
3134
+ // TEST_STATEID cannot expose another client's open state.
2976
3135
  return Status.BAD_STATEID;
3136
+ }
2977
3137
  return checkStateIdSequence(stateid, open);
2978
3138
  });
2979
- return Effect.succeed({
2980
- code: operation.code,
2981
- status: Status.OK,
2982
- body: new Writer().array(results, (writer, status) => writer.uint32(status)).bytes()
2983
- });
3139
+ return Effect.map(xdr.encode(results, XdrCodec.array(XdrCodec.uint32), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)), (body) => ({ code: operation.code, status: Status.OK, body }));
2984
3140
  }
2985
3141
  case "SetSsv":
2986
3142
  // State protection is always SP4_NONE (RFC 8881 Section 18.47.3).
2987
3143
  return Effect.succeed({ code: operation.code, status: Status.INVAL });
2988
3144
  case "Lock": {
2989
- if (current === undefined)
3145
+ if (current === undefined) {
2990
3146
  return Effect.succeed(noCurrent());
3147
+ }
2991
3148
  const value = operation.value;
2992
3149
  const range = lockRange(value.offset, value.length);
2993
- return requireRegularFile(current).pipe(Effect.andThen(Effect.sync(() => {
2994
- if (range === undefined)
3150
+ return requireRegularFile(current).pipe(Effect.andThen(Effect.gen(function* () {
3151
+ if (range === undefined) {
2995
3152
  return { code: operation.code, status: Status.INVAL };
2996
- if (value.reclaim)
3153
+ }
3154
+ if (value.reclaim) {
2997
3155
  return { code: operation.code, status: Status.NO_GRACE };
3156
+ }
2998
3157
  if (WRITE_LOCK_TYPES.has(value.lockType) && !options.writable) {
2999
3158
  return { code: operation.code, status: Status.ROFS };
3000
3159
  }
3001
- if (activeSession === undefined)
3160
+ if (activeSession === undefined) {
3002
3161
  return { code: operation.code, status: Status.BADSESSION };
3162
+ }
3003
3163
  const client = activeSession.client;
3004
3164
  const locker = value.locker;
3005
3165
  let lock;
3006
3166
  let created = false;
3007
3167
  if (locker.kind === "new") {
3008
3168
  const stateid = isCurrentStateId(locker.stateid) ? currentStateid : locker.stateid;
3009
- if (stateid === undefined)
3169
+ if (stateid === undefined) {
3010
3170
  return { code: operation.code, status: Status.BAD_STATEID };
3171
+ }
3011
3172
  const open = opens.get(stateIdKey(stateid));
3012
- if (open === undefined)
3173
+ if (open === undefined) {
3013
3174
  return { code: operation.code, status: Status.BAD_STATEID };
3175
+ }
3014
3176
  const status = checkOpenStateId(stateid, open);
3015
- if (status !== Status.OK)
3177
+ if (status !== Status.OK) {
3016
3178
  return { code: operation.code, status };
3179
+ }
3017
3180
  if ((open.access & (WRITE_LOCK_TYPES.has(value.lockType) ? 2 : 1)) === 0) {
3018
3181
  return { code: operation.code, status: Status.OPENMODE };
3019
3182
  }
@@ -3038,25 +3201,30 @@ export const makeNfs4Handler = (export_, options) => {
3038
3201
  }
3039
3202
  else {
3040
3203
  const stateid = isCurrentStateId(locker.stateid) ? currentStateid : locker.stateid;
3041
- if (stateid === undefined)
3204
+ if (stateid === undefined) {
3042
3205
  return { code: operation.code, status: Status.BAD_STATEID };
3206
+ }
3043
3207
  lock = lockStates.get(stateIdKey(stateid));
3044
- if (lock === undefined)
3208
+ if (lock === undefined) {
3045
3209
  return { code: operation.code, status: Status.BAD_STATEID };
3210
+ }
3046
3211
  const status = checkLockStateId(stateid, lock);
3047
- if (status !== Status.OK)
3212
+ if (status !== Status.OK) {
3048
3213
  return { code: operation.code, status };
3214
+ }
3049
3215
  if ((lock.open.access & (WRITE_LOCK_TYPES.has(value.lockType) ? 2 : 1)) === 0) {
3050
3216
  return { code: operation.code, status: Status.OPENMODE };
3051
3217
  }
3052
3218
  }
3053
3219
  const conflict = conflictingLock(lock.open.reference, lock.client, lock.ownerKey, range, value.lockType);
3054
- if (conflict !== undefined)
3055
- return deniedLock(operation.code, conflict);
3220
+ if (conflict !== undefined) {
3221
+ return yield* deniedLock(operation.code, conflict);
3222
+ }
3056
3223
  const ownerStates = [...lockStates.values()].filter((state) => state.client === lock.client && state.ownerKey === lock.ownerKey &&
3057
3224
  state.open.reference === lock.open.reference);
3058
- if (created)
3225
+ if (created) {
3059
3226
  ownerStates.push(lock);
3227
+ }
3060
3228
  const updates = ownerStates.map((state) => ({
3061
3229
  state,
3062
3230
  next: replaceLockRange(state.ranges, range, state === lock ? (WRITE_LOCK_TYPES.has(value.lockType) ? 2 : 1) : undefined)
@@ -3079,8 +3247,9 @@ export const makeNfs4Handler = (export_, options) => {
3079
3247
  if (changed)
3080
3248
  advanceStateId(lock);
3081
3249
  currentStateid = lock.id;
3082
- return { code: operation.code, status: Status.OK, body: new Writer().fixedOpaque(lock.id).bytes() };
3083
- })), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
3250
+ const body = yield* xdr.encode(lock.id, XdrCodec.fixedOpaque(16), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes));
3251
+ return { code: operation.code, status: Status.OK, body };
3252
+ })), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
3084
3253
  }
3085
3254
  case "Lockt": {
3086
3255
  if (current === undefined)
@@ -3088,7 +3257,7 @@ export const makeNfs4Handler = (export_, options) => {
3088
3257
  const reference = current;
3089
3258
  const value = operation.value;
3090
3259
  const range = lockRange(value.offset, value.length);
3091
- return requireRegularFile(reference).pipe(Effect.map(() => {
3260
+ return requireRegularFile(reference).pipe(Effect.flatMap(() => Effect.gen(function* () {
3092
3261
  if (range === undefined)
3093
3262
  return { code: operation.code, status: Status.INVAL };
3094
3263
  if (WRITE_LOCK_TYPES.has(value.lockType) && !options.writable) {
@@ -3099,8 +3268,8 @@ export const makeNfs4Handler = (export_, options) => {
3099
3268
  const conflict = conflictingLock(reference, activeSession.client, bytesKey(value.owner), range, value.lockType);
3100
3269
  return conflict === undefined
3101
3270
  ? { code: operation.code, status: Status.OK }
3102
- : deniedLock(operation.code, conflict);
3103
- }), Effect.catch((status) => Effect.succeed({ code: operation.code, status })));
3271
+ : yield* deniedLock(operation.code, conflict);
3272
+ })), Effect.catchIf(Predicate.isNumber, (status) => Effect.succeed({ code: operation.code, status })));
3104
3273
  }
3105
3274
  case "Locku": {
3106
3275
  if (current === undefined)
@@ -3134,11 +3303,7 @@ export const makeNfs4Handler = (export_, options) => {
3134
3303
  }
3135
3304
  advanceStateId(lock);
3136
3305
  currentStateid = lock.id;
3137
- return Effect.succeed({
3138
- code: operation.code,
3139
- status: Status.OK,
3140
- body: new Writer().fixedOpaque(lock.id).bytes()
3141
- });
3306
+ return Effect.map(xdr.encode(lock.id, XdrCodec.fixedOpaque(16), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)), (body) => ({ code: operation.code, status: Status.OK, body }));
3142
3307
  }
3143
3308
  case "Close": {
3144
3309
  if (current === undefined)
@@ -3153,8 +3318,9 @@ export const makeNfs4Handler = (export_, options) => {
3153
3318
  if (open === undefined)
3154
3319
  return Effect.succeed({ code: operation.code, status: Status.BAD_STATEID });
3155
3320
  const stateidStatus = checkOpenStateId(stateid, open);
3156
- if (stateidStatus !== Status.OK)
3321
+ if (stateidStatus !== Status.OK) {
3157
3322
  return Effect.succeed({ code: operation.code, status: stateidStatus });
3323
+ }
3158
3324
  if ([...lockStates.values()].some((lock) => lock.open === open && lock.ranges.length > 0)) {
3159
3325
  return Effect.succeed({ code: operation.code, status: Status.LOCKS_HELD });
3160
3326
  }
@@ -3163,18 +3329,14 @@ export const makeNfs4Handler = (export_, options) => {
3163
3329
  // Closing the handle and dropping it from `opens` are one region. An interrupt
3164
3330
  // delivered between them would leave a closed handle in the map for the handler
3165
3331
  // scope's finalizer to close a second time.
3166
- return Effect.uninterruptible(open.close.pipe(Effect.tap(() => Effect.sync(() => {
3332
+ return xdr.encode(closedStateid, XdrCodec.fixedOpaque(16), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)).pipe(Effect.flatMap((body) => Effect.uninterruptible(open.close.pipe(Effect.tap(() => Effect.sync(() => {
3167
3333
  opens.delete(key);
3168
3334
  for (const [lockKey, lock] of lockStates) {
3169
3335
  if (lock.open === open)
3170
3336
  lockStates.delete(lockKey);
3171
3337
  }
3172
3338
  currentStateid = closedStateid;
3173
- })))).pipe(Effect.as({
3174
- code: operation.code,
3175
- status: Status.OK,
3176
- body: new Writer().fixedOpaque(closedStateid).bytes()
3177
- }));
3339
+ })))).pipe(Effect.as({ code: operation.code, status: Status.OK, body }))));
3178
3340
  }
3179
3341
  case "Write": {
3180
3342
  if (current === undefined)
@@ -3208,47 +3370,47 @@ export const makeNfs4Handler = (export_, options) => {
3208
3370
  const writeFile = open.writeFile;
3209
3371
  return statusResult(requireRegularFile(reference).pipe(Effect.andThen(activeCaller === undefined
3210
3372
  ? Effect.void
3211
- : activeCaller.accessReference(reference, 0o2).pipe(Effect.mapError(failureForFs))), Effect.andThen(mapFs(writeFile.pwrite(value.data, value.offset)))), (count) => new Writer().uint32(count).uint32(2).fixedOpaque(writeVerifier).bytes());
3373
+ : activeCaller.accessReference(reference, 0o2).pipe(Effect.mapError(failureForFs))), Effect.andThen(mapFs(writeFile.pwrite(value.data, value.offset)))), (count) => encodeStatusBody(options.limits, [
3374
+ field(XdrCodec.uint32, count),
3375
+ field(XdrCodec.uint32, 2),
3376
+ field(XdrCodec.fixedOpaque(8), writeVerifier)
3377
+ ]));
3212
3378
  }
3213
3379
  case "Setattr": {
3214
- const emptyAttrs = new Writer().uint32(0).bytes();
3215
- if (current === undefined) {
3216
- return Effect.succeed({ ...noCurrent(), body: emptyAttrs });
3217
- }
3218
- if (!options.writable) {
3219
- return Effect.succeed({ code: operation.code, status: Status.ROFS, body: emptyAttrs });
3380
+ if (current === undefined || !options.writable) {
3381
+ return Effect.map(xdr.encode([], XdrCodec.array(XdrCodec.uint32), options.limits, ByteSize.toNumberUnsafe(options.limits.maxRecordBytes)), (body) => ({
3382
+ code: operation.code,
3383
+ status: current === undefined ? Status.NOFILEHANDLE : Status.ROFS,
3384
+ body
3385
+ }));
3220
3386
  }
3221
3387
  const reference = current;
3222
3388
  const value = operation.value;
3223
3389
  return Effect.gen(function* () {
3224
3390
  const applied = [];
3225
- const reply = (status) => ({
3226
- code: operation.code,
3227
- status,
3228
- body: encodeStatusBody((writer) => writeBitmap(writer, wordsFor(applied)))
3229
- });
3230
- const decoded = yield* setattrAttributes(value.attrs, options.limits, supportedAttributes).pipe(Effect.map((changes) => ({ changes })), Effect.catch((status) => Effect.succeed({ status })));
3391
+ const reply = (status) => Effect.map(encodeStatusBody(options.limits, [(writer) => writeBitmap(writer, wordsFor(applied))]), (body) => ({ code: operation.code, status, body }));
3392
+ const decoded = yield* setattrAttributes(value.attrs, options.limits, supportedAttributes).pipe(Effect.mapError((error) => error instanceof XdrDecodeError ? Status.BADXDR : error), Effect.map((changes) => ({ changes })), Effect.catch((status) => Effect.succeed({ status })));
3231
3393
  if ("status" in decoded)
3232
- return reply(decoded.status);
3394
+ return yield* reply(decoded.status);
3233
3395
  if (decoded.changes.some((change) => change.kind === "size")) {
3234
3396
  const stateid = isCurrentStateId(value.stateid) ? currentStateid : value.stateid;
3235
3397
  if (stateid === undefined || isAllZero(stateid) || isAllOnes(stateid)) {
3236
- return reply(Status.BAD_STATEID);
3398
+ return yield* reply(Status.BAD_STATEID);
3237
3399
  }
3238
3400
  const key = stateIdKey(stateid);
3239
3401
  const lock = lockStates.get(key);
3240
3402
  const open = opens.get(key) ?? lock?.open;
3241
3403
  if (open === undefined || open.reference !== reference)
3242
- return reply(Status.BAD_STATEID);
3404
+ return yield* reply(Status.BAD_STATEID);
3243
3405
  const stateStatus = lock === undefined
3244
3406
  ? checkOpenStateId(stateid, open)
3245
3407
  : checkLockStateId(stateid, lock);
3246
3408
  if (stateStatus !== Status.OK)
3247
- return reply(stateStatus);
3409
+ return yield* reply(stateStatus);
3248
3410
  if ((open.access & OPEN4_SHARE_ACCESS_WRITE) === 0)
3249
- return reply(Status.OPENMODE);
3411
+ return yield* reply(Status.OPENMODE);
3250
3412
  if ([...opens.values()].some((state) => state.reference === reference && (state.deny & OPEN4_SHARE_ACCESS_WRITE) !== 0))
3251
- return reply(Status.SHARE_DENIED);
3413
+ return yield* reply(Status.SHARE_DENIED);
3252
3414
  }
3253
3415
  const accessTime = decoded.changes.find((change) => change.attribute === 48);
3254
3416
  const modificationTime = decoded.changes.find((change) => change.attribute === 54);
@@ -3267,12 +3429,12 @@ export const makeNfs4Handler = (export_, options) => {
3267
3429
  });
3268
3430
  const status = yield* mutation.pipe(Effect.as(Status.OK), Effect.catch((error) => Effect.succeed(change.kind === "owner" && error.code === "AccessDenied" ? Status.PERM : failureForFs(error))));
3269
3431
  if (status !== Status.OK)
3270
- return reply(status);
3432
+ return yield* reply(status);
3271
3433
  applied.push(change.attribute);
3272
3434
  if (change.attribute === 48 && modificationTime !== undefined)
3273
3435
  applied.push(54);
3274
3436
  }
3275
- return reply(Status.OK);
3437
+ return yield* reply(Status.OK);
3276
3438
  });
3277
3439
  }
3278
3440
  // Section 15.2 lists NFS4ERR_SYMLINK for LINK but not for CREATE, REMOVE, or RENAME.
@@ -3293,7 +3455,7 @@ export const makeNfs4Handler = (export_, options) => {
3293
3455
  if (!attributes.every((attribute) => supported.includes(attribute))) {
3294
3456
  return yield* Effect.fail(Status.ATTRNOTSUPP);
3295
3457
  }
3296
- const reader = new Reader(value.attrs.values, options.limits);
3458
+ const reader = yield* xdr.openReader(value.attrs.values, options.limits);
3297
3459
  let mode;
3298
3460
  const times = {
3299
3461
  access: { kind: "omit" },
@@ -3301,15 +3463,16 @@ export const makeNfs4Handler = (export_, options) => {
3301
3463
  };
3302
3464
  for (const attribute of attributes) {
3303
3465
  if (attribute === 33) {
3304
- mode = reader.uint32();
3466
+ mode = yield* reader.read(XdrCodec.uint32);
3305
3467
  if (mode > 0o7777)
3306
3468
  return yield* Effect.fail(Status.INVAL);
3307
3469
  }
3308
3470
  else {
3309
- const how = reader.uint32();
3471
+ const how = yield* reader.read(XdrCodec.uint32);
3310
3472
  const time = how === 0 ? { kind: "now" } : {
3311
3473
  kind: "value",
3312
- nanoseconds: BigInt.asIntN(64, reader.uint64()) * 1000000000n + BigInt(reader.uint32())
3474
+ nanoseconds: BigInt.asIntN(64, yield* reader.read(XdrCodec.uint64)) * 1000000000n +
3475
+ BigInt(yield* reader.read(XdrCodec.uint32))
3313
3476
  };
3314
3477
  if (attribute === 48)
3315
3478
  times.access = time;
@@ -3317,7 +3480,7 @@ export const makeNfs4Handler = (export_, options) => {
3317
3480
  times.modification = time;
3318
3481
  }
3319
3482
  }
3320
- reader.finish();
3483
+ yield* reader.finish;
3321
3484
  const result = yield* (value.kind === 2
3322
3485
  ? export_.mkdir(parent, value.name, mode === undefined ? { times } : { mode, times, exactMode: true })
3323
3486
  : export_.symlink(value.target, parent, value.name, { times })).pipe(Effect.mapError((error) => error instanceof ExportCapacityError ?
@@ -3327,10 +3490,10 @@ export const makeNfs4Handler = (export_, options) => {
3327
3490
  : failureForFs(error)));
3328
3491
  setCurrent(result.reference);
3329
3492
  return { change: result.directory, attributes };
3330
- }), ({ change, attributes }) => encodeStatusBody((writer) => {
3331
- writeChangeInfo(writer, change);
3332
- writeBitmap(writer, wordsFor(attributes));
3333
- }));
3493
+ }).pipe(Effect.mapError((error) => error instanceof XdrDecodeError ? Status.BADXDR : error)), ({ change, attributes }) => encodeStatusBody(options.limits, [
3494
+ writeChangeInfo(change),
3495
+ (writer) => writeBitmap(writer, wordsFor(attributes))
3496
+ ]));
3334
3497
  }
3335
3498
  case "Remove": {
3336
3499
  if (current === undefined)
@@ -3342,7 +3505,7 @@ export const makeNfs4Handler = (export_, options) => {
3342
3505
  yield* requireDirectory(directory, Status.NOTDIR);
3343
3506
  yield* validName(operation.value);
3344
3507
  return yield* mapFs(export_.remove(directory, operation.value));
3345
- }), (change) => encodeStatusBody((writer) => writeChangeInfo(writer, change)));
3508
+ }), (change) => encodeStatusBody(options.limits, [writeChangeInfo(change)]));
3346
3509
  }
3347
3510
  case "Rename": {
3348
3511
  if (current === undefined || saved === undefined)
@@ -3361,16 +3524,18 @@ export const makeNfs4Handler = (export_, options) => {
3361
3524
  .pipe(Effect.mapError((error) => error.code === "IsDirectory" || error.code === "NotDirectory" || error.code === "NotEmpty"
3362
3525
  ? Status.EXIST
3363
3526
  : failureForFs(error)));
3364
- }), (change) => encodeStatusBody((writer) => {
3527
+ }), (change) => {
3365
3528
  const sourceChange = Predicate.isTagged(change, "SameDirectory")
3366
3529
  ? change.directory
3367
3530
  : change.sourceDirectory;
3368
3531
  const destinationChange = Predicate.isTagged(change, "SameDirectory")
3369
3532
  ? change.directory
3370
3533
  : change.destinationDirectory;
3371
- writeChangeInfo(writer, sourceChange);
3372
- writeChangeInfo(writer, destinationChange);
3373
- }));
3534
+ return encodeStatusBody(options.limits, [
3535
+ writeChangeInfo(sourceChange),
3536
+ writeChangeInfo(destinationChange)
3537
+ ]);
3538
+ });
3374
3539
  }
3375
3540
  case "Link": {
3376
3541
  if (current === undefined || saved === undefined)
@@ -3383,7 +3548,7 @@ export const makeNfs4Handler = (export_, options) => {
3383
3548
  yield* requireDirectory(destination, Status.SYMLINK);
3384
3549
  yield* validName(operation.value);
3385
3550
  return yield* mapFs(export_.link(source, destination, operation.value));
3386
- }), (result) => encodeStatusBody((writer) => writeChangeInfo(writer, result.directory)));
3551
+ }), (result) => encodeStatusBody(options.limits, [writeChangeInfo(result.directory)]));
3387
3552
  }
3388
3553
  case "NotSupported":
3389
3554
  return Effect.succeed({ code: operation.code, status: Status.NOTSUPP });
@@ -3459,7 +3624,7 @@ export const makeNfs4Handler = (export_, options) => {
3459
3624
  if (!consumedSequence)
3460
3625
  rollbackSequence?.();
3461
3626
  })));
3462
- }).pipe(Effect.orDie);
3627
+ });
3463
3628
  /**
3464
3629
  * Takes the next free backchannel slot. Section 2.10.6.1 requires slot state even for
3465
3630
  * callbacks, so a slot in flight is never reused for a second concurrent callback.
@@ -3490,11 +3655,14 @@ export const makeNfs4Handler = (export_, options) => {
3490
3655
  // previous value and answering the next callback NFS4ERR_SEQ_MISORDERED forever.
3491
3656
  const sequence = nextSequenceId(back.slots[slot].sequence);
3492
3657
  // Section 20.9.3: csa_highest_slotid is the highest slot the server will use.
3493
- const body = encodeCallbackSequence(session.id, sequence, slot, back.slots.length - 1);
3494
- // Section 18.46.3 has SEQUENCE report an unusable callback path. A reply counts only if
3495
- // the client actually handled the callback: PROG_UNAVAIL, AUTH_ERROR and a rejected
3496
- // CB_SEQUENCE are all well-formed replies from a client with no working path.
3497
- const accepted = yield* Effect.ensuring(callback(session, CB_COMPOUND_PROCEDURE, body, (reply) => callbackAccepted(reply, options.limits, session.id, slot, sequence)), Effect.sync(() => {
3658
+ // Section 18.46.3 has SEQUENCE report an unusable callback path. The slot is released
3659
+ // even if encoding the callback body fails before any bytes are sent.
3660
+ const accepted = yield* Effect.ensuring(Effect.gen(function* () {
3661
+ const encodedBody = yield* Effect.result(encodeCallbackSequence(session.id, sequence, slot, back.slots.length - 1, options.limits));
3662
+ if (Result.isFailure(encodedBody))
3663
+ return false;
3664
+ return yield* callback(session, CB_COMPOUND_PROCEDURE, encodedBody.success, (reply) => callbackAccepted(reply, options.limits, session.id, slot, sequence));
3665
+ }), Effect.sync(() => {
3498
3666
  back.slots[slot].busy = false;
3499
3667
  }));
3500
3668
  // A re-arm while this probe was in flight means its verdict is about a path the client