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