001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server;
018
019import static org.apache.juneau.commons.function.Suppliers.*;
020import static org.apache.juneau.commons.httppart.HttpPartType.*;
021import static org.apache.juneau.commons.reflect.AnnotationTraversal.*;
022import static org.apache.juneau.commons.utils.CollectionUtils.*;
023import static org.apache.juneau.commons.utils.Shorts.*;
024import static org.apache.juneau.commons.utils.StringUtils.*;
025import static org.apache.juneau.commons.utils.StringUtils.isNotEmpty;
026import static org.apache.juneau.commons.utils.ThrowableUtils.*;
027import static org.apache.juneau.rest.server.util.RestUtils.*;
028
029import java.lang.annotation.*;
030import java.lang.reflect.Method;
031import java.nio.charset.*;
032import java.util.*;
033import java.util.concurrent.*;
034import java.util.function.*;
035import java.util.logging.*;
036import java.util.stream.*;
037
038import org.apache.juneau.commons.*;
039import org.apache.juneau.commons.collections.*;
040import org.apache.juneau.commons.function.*;
041import org.apache.juneau.commons.http.*;
042import org.apache.juneau.commons.inject.*;
043import org.apache.juneau.commons.lang.*;
044import org.apache.juneau.commons.logging.*;
045import org.apache.juneau.commons.reflect.*;
046import org.apache.juneau.commons.svl.*;
047import org.apache.juneau.commons.utils.*;
048import org.apache.juneau.http.*;
049import org.apache.juneau.http.header.*;
050import org.apache.juneau.http.part.*;
051import org.apache.juneau.http.response.*;
052import org.apache.juneau.httppart.bean.*;
053import org.apache.juneau.marshall.*;
054import org.apache.juneau.marshall.encoders.*;
055import org.apache.juneau.marshall.httppart.*;
056import org.apache.juneau.marshall.jsonschema.*;
057import org.apache.juneau.marshall.parser.*;
058import org.apache.juneau.marshall.serializer.*;
059import org.apache.juneau.rest.common.utils.*;
060import org.apache.juneau.rest.server.converter.*;
061import org.apache.juneau.rest.server.guard.*;
062import org.apache.juneau.rest.server.httppart.*;
063import org.apache.juneau.rest.server.matcher.*;
064import org.apache.juneau.rest.server.util.*;
065
066import jakarta.servlet.*;
067import jakarta.servlet.http.*;
068
069/**
070 * Represents a single Java servlet/resource method annotated with {@link RestOp @RestOp}.
071 *
072 * <h2 class='section'>Notes:</h2><ul>
073 *    <li class='note'>This class is thread safe and reusable.
074 * </ul>
075 *
076 * <h2 class='section'>See Also:</h2><ul>
077 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestOpContext">RestOpContext</a>
078 * </ul>
079 */
080@SuppressWarnings({
081   "java:S112", // throws Exception intentional - callback/lifecycle methods throughout this class
082   "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants
083   "java:S1200", // High coupling is intentional in this central operation context aggregator.
084   "java:S3776", // Branching is inherent to the RestOpContext constructor and compareTo(), which resolve many annotation-driven settings and ordering keys.
085   "java:S6539", // RestOpContext intentionally centralizes op wiring and annotation resolution.
086   "rawtypes", // Raw types necessary for generic type handling.
087   "resource", // op-level BasicBeanStores are short-lived scratch stores; the long-lived opBeanStore field is owned and closed by the parent RestContext via its bean-store hierarchy.
088   "unchecked" // Cast is safe: type parameter is verified by caller context.
089})
090public class RestOpContext extends Context implements Comparable<RestOpContext> {
091
092   // Argument name constants for req*
093
094   private static final AnnotationProvider AP = AnnotationProvider.INSTANCE;
095
096   /**
097    * Env-driven default charset for this operation, populated by {@link ClassInfo#inject(Object, BeanStore)}
098    * before the {@link #defaultCharset} memoizer fires; resolved from {@code RestContext.defaultCharset} or
099    * {@code "UTF-8"}.
100    */
101   @Value("${RestContext.defaultCharset:UTF-8}")
102   private String defaultCharsetName;
103
104   /**
105    * Env-driven default max-input string for this operation, populated by {@link ClassInfo#inject(Object, BeanStore)}
106    * before the {@link #maxInput} memoizer fires; resolved from {@code RestContext.maxInput} or
107    * {@code "1000000"} &mdash; matching the {@code @Rest}-level fallback in
108    * {@link org.apache.juneau.rest.server.config.DefaultConfig DefaultConfig} so an operation that falls all the
109    * way through to this last-resort default doesn't end up with a substantially larger effective ceiling than
110    * the class-level default.
111    */
112   @Value("${RestContext.maxInput:1000000}")
113   private String defaultMaxInputString;
114
115   /**
116    * Internal construction-time state holder.
117    */
118   static class Builder extends Context.Builder {
119
120      private final Method restMethod;
121      private final RestContext restContext;
122      private final Supplier<Object> restResourceSupplier;
123
124      Builder(Method method, RestContext context) {
125         this(method, context, null);
126      }
127
128      Builder(Method method, RestContext context, Supplier<Object> resourceSupplier) {
129
130         this.restContext = context;
131         this.restMethod = method;
132         this.restResourceSupplier = resourceSupplier == null ? context::getResource : resourceSupplier;
133
134         var ap = context.getMarshallingContext().getAnnotationProvider();
135         var mi = MethodInfo.of(context.getResourceClass(), method);
136         var resourceClass = ClassInfo.of(context.getResourceClass());
137
138         try {
139            var vr = context.getVarResolver();
140            var vrs = vr.createSession();
141
142            // Parent-to-child merge: class-level annotations (parent class chain) applied first, then method-level
143            // (matching-methods chain, return type, package). Method annotations thus override class annotations
144            // for the same property. LinkedHashSet deduplicates while preserving order.
145            //
146            // For a mixin op (the op's context is a mixin sub-context), the host's class-level @ContextApply
147            // config (e.g. @HtmlDocConfig, @SerializerConfig) is prepended ahead of the mixin class's own class
148            // annotations, so the effective precedence is method > mixin-class > host-class. This is the
149            // op-level counterpart of the context-level inheritance walk and is gated by @Rest(noInherit) on
150            // the mixin. For non-mixin contexts the host stream is empty (no behavior change).
151            var hostClassAnnotations = context.getInheritedHostClassAnnotations(ap);
152            var declaringClassAnnotations = rstream(ap.find(resourceClass, SELF, PARENTS));
153            var methodAnnotations = rstream(ap.find(mi, SELF, MATCHING_METHODS, RETURN_TYPE, PACKAGE));
154            var allAnnotationsSet = new LinkedHashSet<AnnotationInfo<?>>();
155            hostClassAnnotations.forEach(allAnnotationsSet::add);
156            declaringClassAnnotations.forEach(allAnnotationsSet::add);
157            methodAnnotations.forEach(allAnnotationsSet::add);
158            var work = AnnotationWorkList.of(vrs, allAnnotationsSet.stream().filter(CONTEXT_APPLY_FILTER));
159
160            apply(work);
161
162         } catch (Exception e) {
163            throw new InternalServerError(e);
164         }
165      }
166
167      @Override /* Overridden from Context.Builder<?> */
168      public Builder copy() {
169         throw new NoSuchMethodError("Not implemented.");
170      }
171   }
172
173   private static HttpPartSerializer createPartSerializer(Class<? extends HttpPartSerializer> c, HttpPartSerializer defaultSerializer) {
174      return c == null
175         ? defaultSerializer
176         : BeanInstantiator.of(HttpPartSerializer.class).type(c).fallback(() -> defaultSerializer).run();
177   }
178
179   private final WritableBeanStore opBeanStore;
180   protected final Map<Class<?>,ResponseBeanMeta> responseBeanMetas = new ConcurrentHashMap<>();
181   protected final Map<Class<?>,ResponsePartMeta> headerPartMetas = new ConcurrentHashMap<>();
182   protected final Method method;
183   protected final MethodInfo mi;
184   protected final RestContext context;
185   private final Supplier<Object> resourceSupplier;
186
187   // The annotation work-list produced during construction.
188   private final AnnotationWorkList appliedAnnotations;
189
190   private RestContext restContext() { return context; }
191
192   /**
193    * Returns the {@link RestContext} that owns this operation context.
194    *
195    * <p>
196    * For operations declared directly on the host resource class, returns the host context. For operations
197    * registered through a {@code @Rest(mixins=...)} mixin, returns the per-mixin sub-context (parent-linked
198    * to the host's context via {@link RestContext#getParentContext()}). Callers can use this to identify
199    * whether the operation was contributed by a mixin (via {@link RestContext#isMixinContext()}).
200    *
201    * @return The owning {@link RestContext} for this operation.
202    * @since 10.0.0
203    */
204   public RestContext getContext() { return context; }
205
206   private Method method() { return method; }
207   private MethodInfo methodInfo() { return mi; }
208   private AnnotationWorkList appliedAnnotations() { return appliedAnnotations; }
209   private BeanStore beanStore() { return context.getBeanStore(); }
210   private WritableBeanStore opBeanStore() { return opBeanStore; }
211   private Object resource() { return resourceSupplier.get(); }
212   private VarResolver varResolver() { return context.getVarResolver(); }
213
214   //-----------------------------------------------------------------------------------------------------------------
215   // Memoized fields
216   //-----------------------------------------------------------------------------------------------------------------
217
218   /** Effective allowed parser session-option keys for this operation. */
219   private final Memoizer<SortedSet<String>> allowedParserOptions = memoizer(() -> {
220      var l = new ArrayList<String>();
221      var p = "allowedParserOptions";
222      if (isInherited(p))
223         l.addAll(restContext().getAllowedParserOptions());
224      getRestOpAnnotations().stream()
225         .flatMap(ai -> resolveCdl(ai.getStringArray(p).orElse(EMPTY_STRING_ARRAY)))
226         .forEach(l::add);
227      return u(treeSetCi(removeNegations(l)));
228   });
229
230   /** Effective allowed serializer session-option keys for this operation. */
231   private final Memoizer<SortedSet<String>> allowedSerializerOptions = memoizer(() -> {
232      var l = new ArrayList<String>();
233      var p = "allowedSerializerOptions";
234      if (isInherited(p))
235         l.addAll(restContext().getAllowedSerializerOptions());
236      getRestOpAnnotations().stream()
237         .flatMap(ai -> resolveCdl(ai.getStringArray(p).orElse(EMPTY_STRING_ARRAY)))
238         .forEach(l::add);
239      return u(treeSetCi(removeNegations(l)));
240   });
241
242   /** The {@link MarshallingContext} for this operation (op-level annotations applied on top of the parent context). */
243   private final Memoizer<MarshallingContext> marshallingContext = memoizer(() -> {
244      var aa = appliedAnnotations();
245      var parent = restContext().getBeanContextBuilder();
246      if (!parent.canApply(aa))
247         return restContext().getMarshallingContext();
248      Holder<MarshallingContext.Builder> v = Holder.of(parent.copy());
249      v.get().apply(aa);
250      var bs = new BasicBeanStore(beanStore())
251         .addBean(Method.class, method())
252         .addBean(MarshallingContext.Builder.class, v.get());
253      bs.createBeanFromMethod(MarshallingContext.class, resource(), this::matchesInjectScope)
254         .ifPresent(x -> v.get().impl(x));
255      return v.get().build();
256   });
257
258   /**
259    * The per-operation logger for debug capture.
260    *
261    * <p>
262    * A hierarchical child of the <b>host</b> resource's {@linkplain RestContext#getLogger() resolved logger}
263    * ({@code <hostLoggerName>.<methodName>}) so an operator can raise the debug level for a single operation
264    * without affecting its siblings (JUL parent-level inheritance). Deriving from the resolved logger &mdash;
265    * rather than the raw resource class name &mdash; means a bean-store {@code RichLogger} override on the host
266    * (see {@link RestContext#getLogger()}) is honored: the op logger is a true JUL child of whatever logger the
267    * host actually resolves to, not a same-named-but-unrelated sibling.
268    *
269    * <p>
270    * For an operation contributed by a composed {@linkplain Rest#mixins() mixin}, the host is the <b>host /
271    * top-level resource</b> &mdash; not the mixin class &mdash; so raising the host resource's JUL level cascades
272    * to its mixin-served operations, and the same mixin composed into different hosts resolves to distinct,
273    * host-isolated loggers.  Non-mixin operations (including child resources, which are their own resources)
274    * resolve to their own resource's logger as before.
275    */
276   private final Memoizer<RichLogger> logger = memoizer(() ->
277      RichLogger.getLogger(hostRestContext().getLogger().getName() + "." + getJavaMethod().getName()));
278
279   /**
280    * Returns the host / top-level resource context for logger naming.
281    *
282    * <p>
283    * When this operation's context originates from a {@linkplain RestContext#isMixinContext() mixin sub-context},
284    * walks up the {@linkplain RestContext#getParentContext() parent-context} linkage past any composed mixin
285    * sub-contexts to the host resource that composed the mixin.  Non-mixin contexts (including child resources)
286    * return their own context unchanged.
287    *
288    * @return The host resource context.
289    */
290   private RestContext hostRestContext() {
291      var rc = restContext();
292      while (rc.isMixinContext() && rc.getParentContext() != null)
293         rc = rc.getParentContext();
294      return rc;
295   }
296
297   /**
298    * The response-converter array for this operation.
299    *
300    * <p>
301    * Walks the {@code @Rest(converters)} class chain (parent-to-child) followed by the
302    * {@code @RestOp(converters)} method chain (parent-to-child). Op-level
303    * {@code noInherit={"converters"}} cuts off the class-chain contribution. An
304    * {@code @Bean RestConverterList} bean (either as a name-anonymous bean in the bean store
305    * or as a {@code @Bean} method whose {@code methodScope} matches this operation's method
306    * name) REPLACES the entire annotation-derived list.
307    */
308   private final Memoizer<RestConverter[]> converters = memoizer(() -> {
309      var bs = beanStore();
310      var b = RestConverterList.create(bs);
311      if (isInherited("converters"))
312         restContext().getRestAnnotationsForProperty("converters")
313            .forEach(ai -> b.append(ai.inner().converters()));
314      getRestOpAnnotationsForProperty("converters")
315         .forEach(ai -> ai.getClassArray("converters", RestConverter.class).ifPresent(classes -> {
316            for (var c : classes)
317               b.append(classArray(c));
318         }));
319      var override = bs.createBeanFromMethod(RestConverterList.class, resource(), this::matchesInjectScope).orElse(null);
320      if (override == null)
321         override = bs.getBean(RestConverterList.class).orElse(null);
322      return (nn(override) ? override : b.build()).asArray();
323   });
324
325   /** The effective default {@link Charset} for this operation, resolved from op annotations, context, or env. */
326   private final Memoizer<Charset> defaultCharset = memoizer(() -> {
327      var v = findOpString("defaultCharset");
328      if (v.isPresent())
329         return Charset.forName(v.get());
330      if (isInherited("defaultCharset")) {
331         var rv = restContext().mergeReplacedStringAttribute("defaultCharset", null);
332         if (ine(rv))
333            return Charset.forName(rv);
334      }
335      return Charset.forName(defaultCharsetName);
336   });
337
338   /**
339    * The default request attribute map for this operation.
340    *
341    * <p>
342    * Starts with the class-level value (which already incorporates
343    * {@code @Rest(defaultRequestAttributes)}), then walks the {@code @RestOp}/verb chain
344    * (parent-to-child) and adds each entry — {@link NamedAttributeMap#add} uses put-semantics so
345    * child entries override parent entries by name. An
346    * {@code @Bean(name="defaultRequestAttributes") NamedAttributeMap} bean (matching this
347    * operation's method scope) REPLACES the entire result.
348    */
349   private final Memoizer<NamedAttributeMap> defaultRequestAttributes = memoizer(() -> {
350      var v = Holder.of(restContext().getDefaultRequestAttributes().copy());
351      getRestOpAnnotationsForProperty("defaultRequestAttributes").forEach(ai -> {
352         for (var s : ai.getStringArray("defaultRequestAttributes").orElse(EMPTY_STRING_ARRAY))
353            v.get().add(BasicNamedAttribute.ofPair(s));
354      });
355      beanStore().createBeanFromMethod(NamedAttributeMap.class, resource(), x -> matchesInjectScope(x, "defaultRequestAttributes"))
356         .ifPresent(v::set);
357      return v.get();
358   });
359
360   /**
361    * The default request form-data parts for this operation.
362    *
363    * <p>
364    * Walks the {@code @RestOp}/verb chain (parent-to-child); each {@code defaultRequestFormData}
365    * entry is applied with {@link PartList#setDefault} (first-in-chain wins per name).
366    * Method-parameter {@link FormData @FormData} annotations with a
367    * {@link Schema#default_()}/{@link Schema#df()} default are folded in last (also
368    * {@code setDefault} = first wins). An {@code @Bean(name="defaultRequestFormData") PartList}
369    * bean (matching this operation's method scope) REPLACES the entire result.
370    */
371   private final Memoizer<HttpPartList> defaultRequestFormData = memoizer(() -> {
372      var v = Holder.of(HttpPartList.create());
373      getRestOpAnnotationsForProperty("defaultRequestFormData").forEach(ai -> {
374         for (var s : ai.getStringArray("defaultRequestFormData").orElse(EMPTY_STRING_ARRAY))
375            v.get().setDefault(HttpStringPart.ofPair(s));
376      });
377      processParameterDefaults((paramAnn, def) -> {
378         if (paramAnn instanceof FormData paramAnn2) {
379            try {
380               v.get().setDefault(HttpStringPart.of(firstNonEmpty(paramAnn2.name(), paramAnn2.value()), toPartValue(parseIfJson(def))));
381            } catch (ParseException e) {
382               throw new ConfigException(e, "Malformed @FormData annotation");
383            }
384         }
385      });
386      beanStore().createBeanFromMethod(HttpPartList.class, resource(), x -> matchesInjectScope(x, "defaultRequestFormData"))
387         .ifPresent(v::set);
388      return v.get();
389   });
390
391   /**
392    * The default request headers for this operation.
393    *
394    * <p>
395    * Starts with the class-level value (which already incorporates
396    * {@code @Rest(defaultRequestHeaders|defaultAccept|defaultContentType)}), then walks the
397    * {@code @RestOp}/verb chain (parent-to-child); each annotation's {@code defaultRequestHeaders}
398    * entries plus its {@code defaultAccept} / {@code defaultContentType} (folded into
399    * {@code Accept} / {@code Content-Type} headers) are applied with {@link HeaderList#setDefault}
400    * (first-in-chain wins per name — class-level beats op-level beats later op-level entries).
401    *
402    * <p>
403    * Method-parameter {@link Header @Header} annotations with a
404    * {@link Schema#default_()}/{@link Schema#df()} default are folded in last via
405    * {@link HeaderList#set} (overrides any prior entry with the same name). An
406    * {@code @Bean(name="defaultRequestHeaders") HeaderList} bean (matching this operation's
407    * method scope) REPLACES the entire result.
408    */
409   private final Memoizer<HttpHeaderList> defaultRequestHeaders = memoizer(() -> {
410      var v = Holder.of(restContext().getDefaultRequestHeaders().copy());
411      getRestOpAnnotationsForProperty("defaultRequestHeaders").forEach(ai -> {
412         for (var s : ai.getStringArray("defaultRequestHeaders").orElse(EMPTY_STRING_ARRAY))
413            v.get().setDefault(HttpStringHeader.ofPair(s));
414         ai.getString("defaultAccept").filter(s -> !s.isEmpty()).ifPresent(s -> v.get().setDefault(Accept.of(s)));
415         ai.getString("defaultContentType").filter(s -> !s.isEmpty()).ifPresent(s -> v.get().setDefault(ContentType.of(s)));
416      });
417      processParameterDefaults((paramAnn, def) -> {
418         if (paramAnn instanceof Header paramAnn2) {
419            try {
420               v.get().set(HttpStringHeader.of(firstNonEmpty(paramAnn2.name(), paramAnn2.value()), toPartValue(parseIfJson(def))));
421            } catch (ParseException e) {
422               throw new ConfigException(e, "Malformed @Header annotation");
423            }
424         }
425      });
426      beanStore().createBeanFromMethod(HttpHeaderList.class, resource(), x -> matchesInjectScope(x, "defaultRequestHeaders"))
427         .ifPresent(v::set);
428      return v.get();
429   });
430
431   /**
432    * The default request query-data parts for this operation.
433    *
434    * <p>
435    * Walks the {@code @RestOp}/verb chain (parent-to-child); each {@code defaultRequestQueryData}
436    * entry is applied with {@link PartList#setDefault} (first-in-chain wins per name).
437    * Method-parameter {@link Query @Query} annotations with a
438    * {@link Schema#default_()}/{@link Schema#df()} default are folded in last (also
439    * {@code setDefault} = first wins). An {@code @Bean(name="defaultRequestQueryData") PartList}
440    * bean (matching this operation's method scope) REPLACES the entire result.
441    */
442   private final Memoizer<HttpPartList> defaultRequestQueryData = memoizer(() -> {
443      var v = Holder.of(HttpPartList.create());
444      getRestOpAnnotationsForProperty("defaultRequestQueryData").forEach(ai -> {
445         for (var s : ai.getStringArray("defaultRequestQueryData").orElse(EMPTY_STRING_ARRAY))
446            v.get().setDefault(HttpStringPart.ofPair(s));
447      });
448      processParameterDefaults((paramAnn, def) -> {
449         if (paramAnn instanceof Query paramAnn2) {
450            try {
451               v.get().setDefault(HttpStringPart.of(firstNonEmpty(paramAnn2.name(), paramAnn2.value()), toPartValue(parseIfJson(def))));
452            } catch (ParseException e) {
453               throw new ConfigException(e, "Malformed @Query annotation");
454            }
455         }
456      });
457      beanStore().createBeanFromMethod(HttpPartList.class, resource(), x -> matchesInjectScope(x, "defaultRequestQueryData"))
458         .ifPresent(v::set);
459      return v.get();
460   });
461
462   /**
463    * The default response headers for this operation.
464    *
465    * <p>
466    * Starts with the class-level value (which already incorporates
467    * {@code @Rest(defaultResponseHeaders)}), then walks the {@code @RestOp}/verb chain
468    * (parent-to-child); each annotation's {@code defaultResponseHeaders} entries are applied with
469    * {@link HeaderList#setDefault} (first-in-chain wins per name). An
470    * {@code @Bean(name="defaultResponseHeaders") HeaderList} bean (matching this operation's
471    * method scope) REPLACES the entire result.
472    */
473   private final Memoizer<HttpHeaderList> defaultResponseHeaders = memoizer(() -> {
474      var v = Holder.of(restContext().getDefaultResponseHeaders().copy());
475      getRestOpAnnotationsForProperty("defaultResponseHeaders").forEach(ai -> {
476         for (var s : ai.getStringArray("defaultResponseHeaders").orElse(EMPTY_STRING_ARRAY))
477            v.get().setDefault(HttpStringHeader.ofPair(s));
478      });
479      beanStore().createBeanFromMethod(HttpHeaderList.class, resource(), x -> matchesInjectScope(x, "defaultResponseHeaders"))
480         .ifPresent(v::set);
481      return v.get();
482   });
483
484   /**
485    * The encoder group for this operation.
486    *
487    * <p>
488    * Walks the {@code @RestOp(encoders)} chain (parent-to-child); each non-empty {@code encoders()}
489    * array REPLACES the inherited set (with {@link Inherit} as a sentinel that re-injects the prior
490    * set's entries at the specified position — matches the legacy {@code EncoderSet.Builder.set(...)}
491    * semantics). Falls through to the class-level {@link RestContext#getEncoders()} when no op
492    * annotation declares encoders. An {@code @Bean EncoderSet} bean (matching this operation's
493    * method scope) REPLACES the result entirely.
494    */
495   private final Memoizer<EncoderSet> encoders = memoizer(() -> {
496      var bs = beanStore();
497      var b = restContext().getEncodersBuilder().copy();
498      getRestOpAnnotationsForProperty("encoders").forEach(ai -> {
499         var c = ai.getClassArray("encoders", Encoder.class).orElse(null);
500         if (nn(c) && c.length > 0)
501            b.set(c);
502      });
503      var v = Holder.of(b.build());
504      bs.createBeanFromMethod(EncoderSet.class, resource(), this::matchesInjectScope)
505         .ifPresent(v::set);
506      return v.get();
507   });
508
509   /**
510    * The request-guard array for this operation. <b>Cross-bucket memoizer</b> — folds three
511    * annotation attributes ({@code guards}, {@code roleGuard}, {@code rolesDeclared}) into a
512    * single effective {@link RestGuardList}.
513    *
514    * <p>
515    * Walk order: class {@code @Rest} chain (parent-to-child, gated by op-level
516    * {@code noInherit={"guards"}}), then op {@code @RestOp} chain (parent-to-child). Concretely:
517    * <ul>
518    *    <li>Each annotation contributes its {@code guards()} classes (appended in chain order).
519    *    <li>Each annotation contributes its {@code rolesDeclared()} CDL into a single role-name set.
520    *    <li>Each annotation contributes its {@code roleGuard()} string (when non-blank). Each
521    *       non-blank {@code roleGuard} becomes a {@link RoleBasedRestGuard} appended to the list,
522    *       using the accumulated {@code rolesDeclared} set as its allow-list.
523    * </ul>
524    *
525    * <p>
526    * An {@code @Bean RestGuardList} bean (via the bean store or an {@code @Bean} method
527    * with matching {@code methodScope}) REPLACES the entire annotation-derived list.
528    */
529   private final Memoizer<RestGuard[]> guards = memoizer(() -> {
530      var bs = beanStore();
531      var b = RestGuardList.create(bs);
532      var rolesDeclaredSet = new LinkedHashSet<String>();
533      var roleGuardStrs = new ArrayList<String>();
534
535      Consumer<AnnotationInfo<?>> walk = ai -> {
536         ai.getClassArray("guards", RestGuard.class).ifPresent(classes -> {
537            for (var c : classes)
538               b.append(classArray(c));
539         });
540         // rolesDeclared is a single CDL string (not an array) on every annotation in the chain.
541         ai.getString("rolesDeclared").filter(StringUtils::isNotBlank)
542            .ifPresent(s -> resolveCdl(s).forEach(rolesDeclaredSet::add));
543         ai.getString("roleGuard").filter(StringUtils::isNotBlank).ifPresent(roleGuardStrs::add);
544      };
545
546      if (isInherited("guards"))
547         restContext().getRestAnnotationsForProperty("guards").forEach(walk::accept);
548      getRestOpAnnotationsForProperty("guards").forEach(walk);
549
550      // When no @Rest/@RestOp(rolesDeclared) is set, pass null so RoleBasedRestGuard
551      // infers role names from the expression itself (legacy semantics — an empty
552      // declared-role set would silently never match).
553      var declaredRoles = rolesDeclaredSet.isEmpty() ? null : rolesDeclaredSet;
554      for (var rg : roleGuardStrs) {
555         try {
556            b.append(new RoleBasedRestGuard(declaredRoles, rg));
557         } catch (java.text.ParseException e) {
558            throw toRex(e);
559         }
560      }
561
562      var override = bs.createBeanFromMethod(RestGuardList.class, resource(), this::matchesInjectScope).orElse(null);
563      if (override == null)
564         override = bs.getBean(RestGuardList.class).orElse(null);
565      return (nn(override) ? override : b.build()).asArray();
566   });
567
568   /** The depth of the declaring class in the inheritance chain. */
569   private final Memoizer<Integer> hierarchyDepth = memoizer(() -> {
570      int hierarchyDepthTemp = 0;
571      var sc = method().getDeclaringClass().getSuperclass();
572      while (nn(sc)) {
573         hierarchyDepthTemp++;
574         sc = sc.getSuperclass();
575      }
576      return hierarchyDepthTemp;
577   });
578
579   /**
580    * The {@code @RestOp}-group annotation that supplies this operation's HTTP method.
581    *
582    * <p>
583    * Walks {@code @RestOp}-group annotations child-to-parent; verb-specific annotations
584    * ({@link RestGet}, etc.) imply their fixed verb. Empty when no annotation declares a verb, in which case the
585    * verb is inferred from the Java method name.
586    */
587   private final Memoizer<Optional<AnnotationInfo<?>>> httpMethodSource = memoizer(() -> {
588      var vr = varResolver();
589      for (var ai : getRestOpAnnotations())
590         if (ine(httpMethodFromAnnotation(ai.inner(), vr)))
591            return o(ai);
592      return oe();
593   });
594
595   /**
596    * The HTTP method string for this operation (e.g. {@code "GET"}, {@code "*"}).
597    *
598    * <p>
599    * Taken from {@link #httpMethodSource}. Falls back to {@link HttpUtils#detectHttpMethod} when no annotation
600    * declares a verb.
601    */
602   private final Memoizer<String> httpMethod = memoizer(() ->
603      normalizeHttpMethod(httpMethodSource.get()
604         .map(ai -> httpMethodFromAnnotation(ai.inner(), varResolver()))
605         .orElseGet(() -> HttpUtils.detectHttpMethod(method(), true, "GET"))));
606
607   /**
608    * Whether this operation is declared {@link RestOp#read() read=true}.
609    *
610    * <p>
611    * Read from the annotation that supplies the HTTP method, so the verb and its read declaration travel together.
612    * When the verb is inferred, it comes from the nearest {@link RestOp @RestOp}. A {@code read=true} on an
613    * overridden annotation that names its own verb is replaced along with that verb. One on another
614    * {@link RestOp @RestOp} that names no verb would be silently ignored, so it fails the operation.
615    */
616   private final Memoizer<Boolean> read = memoizer(() -> {
617      var vr = varResolver();
618      var annotations = getRestOpAnnotations();
619      var source = httpMethodSource.get()
620         .orElseGet(() -> annotations.stream().filter(x -> x.inner() instanceof RestOp).findFirst().orElse(null));
621      for (var ai : annotations) {
622         // An annotation that names its own verb but was overridden by a nearer one is replaced along with its read.
623         // One that names no verb would have its read silently ignored, so that is refused.
624         if (ai != source && ai.inner() instanceof RestOp a2 && a2.read() && ! ine(httpMethodFromAnnotation(a2, vr)))
625            throw new InternalServerError(
626               "Operation '" + method().getDeclaringClass().getSimpleName() + "." + method().getName()
627               + "' declares @RestOp(read=true) on an annotation that does not supply its method '" + getHttpMethod() + "'."
628               + " The read declaration is taken only from the annotation that names the method."
629               + " Move read=true to that annotation, or remove it.");
630      }
631      return nn(source) && source.inner() instanceof RestOp a2 && a2.read();
632   });
633
634   /** The JSON-Schema generator for this operation (op-level annotations applied on top of the parent). */
635   private final Memoizer<JsonSchemaGenerator> jsonSchemaGenerator = memoizer(() -> {
636      var aa = appliedAnnotations();
637      var parent = restContext().getJsonSchemaGeneratorBuilder();
638      if (!parent.canApply(aa))
639         return restContext().getJsonSchemaGenerator();
640      Holder<JsonSchemaGenerator.Builder> v = Holder.of(parent.copy());
641      v.get().apply(aa);
642      var bs = new BasicBeanStore(beanStore())
643         .addBean(Method.class, method())
644         .addBean(JsonSchemaGenerator.Builder.class, v.get());
645      bs.createBeanFromMethod(JsonSchemaGenerator.class, resource(), this::matchesInjectScope)
646         .ifPresent(x -> v.get().impl(x));
647      return v.get().build();
648   });
649
650   /**
651    * The request-matcher list for this operation. <b>Cross-bucket memoizer</b> — folds
652    * {@code matchers} and {@code clientVersion} (both op-level only) into a single effective
653    * {@link RestMatcherList}.
654    *
655    * <p>
656    * Walks the {@code @RestOp}/verb annotation chain (parent-to-child, gated by op-level
657    * {@code noInherit={"matchers"}}). Each annotation contributes its {@code matchers()} classes
658    * (appended in chain order). The final non-blank {@code clientVersion()} (most-derived wins)
659    * appends a single {@link ClientVersionMatcher} keyed off the resource's client-version header.
660    * An {@code @Bean RestMatcherList} bean (via the bean store or an {@code @Bean}
661    * method with matching {@code methodScope}) REPLACES the entire annotation-derived list.
662    */
663   private final Memoizer<RestMatcherList> matchersList = memoizer(() -> {
664      var bs = beanStore();
665      var b = RestMatcherList.create(bs);
666      var clientVersion = new String[]{null};
667
668      getRestOpAnnotationsForProperty("matchers").forEach(ai -> {
669         ai.getClassArray("matchers", RestMatcher.class).ifPresent(classes -> {
670            for (var c : classes)
671               b.append(classArray(c));
672         });
673         ai.getString("clientVersion").filter(StringUtils::isNotBlank).ifPresent(s -> clientVersion[0] = s);
674      });
675
676      if (nn(clientVersion[0]))
677         b.append(new ClientVersionMatcher(restContext().getClientVersionHeader(), MethodInfo.of(method())));
678
679      var override = bs.createBeanFromMethod(RestMatcherList.class, resource(), this::matchesInjectScope).orElse(null);
680      if (override == null)
681         override = bs.getBean(RestMatcherList.class).orElse(null);
682      return nn(override) ? override : b.build();
683   });
684
685   /** The invoker for the operation method itself. */
686   private final Memoizer<RestOpInvoker> methodInvoker = memoizer(() ->
687      new RestOpInvoker(method(), restContext().findRestOperationArgs(method(), opBeanStore()), restContext().getMethodExecStats(method()), this::resource)
688   );
689
690   private static final long DEFAULT_MAX_INPUT = 1_000_000L;
691
692   /** The effective max-input byte limit for this operation. */
693   private final Memoizer<Long> maxInput = memoizer(() -> {
694      long n;
695      var v = findOpString("maxInput");
696      var rv = isInherited("maxInput") ? restContext().mergeReplacedStringAttribute("maxInput", null) : null;
697      if (v.isPresent())
698         n = parseLongWithSuffix(v.get());
699      else if (ine(rv))
700         n = parseLongWithSuffix(rv);
701      else
702         n = parseLongWithSuffix(defaultMaxInputString);
703      // A zero or negative value means "use the default" rather than "unlimited".
704      return n > 0 ? n : DEFAULT_MAX_INPUT;
705   });
706   /**
707    * Whether this operation emits RFC 7807 {@code application/problem+json} responses.
708    *
709    * <p>
710    * Tri-state semantics on the {@code @RestOp}-group annotations:
711    * <ul>
712    *    <li>{@code "true"} &mdash; opt this operation in.
713    *    <li>{@code "false"} &mdash; opt this operation out (overrides an opted-in resource).
714    *    <li>{@code ""} (default) &mdash; inherit from the resource-level {@code @Rest(problemDetails)}.
715    * </ul>
716    */
717   private final Memoizer<Boolean> problemDetails = memoizer(() -> {
718      var v = findOpString("problemDetails");
719      if (v.isPresent())
720         return Boolean.parseBoolean(v.get());
721      if (isInherited("problemDetails"))
722         return restContext().isProblemDetails();
723      return false;
724   });
725
726   /**
727    * Whether REST-driven serializer/parser debug behavior is enabled for this operation.
728    *
729    * <p>
730    * Tri-state semantics on the {@code @RestOp}-group annotations:
731    * <ul>
732    *    <li>{@code "true"} &mdash; opt this operation in.
733    *    <li>{@code "false"} &mdash; opt this operation out (overrides an opted-in resource).
734    *    <li>{@code ""} (default) &mdash; inherit from the resource-level {@code @Rest(debugMarshalling)}.
735    * </ul>
736    */
737   private final Memoizer<Boolean> debugMarshalling = memoizer(() -> {
738      var v = findOpString("debugMarshalling");
739      if (v.isPresent())
740         return Boolean.parseBoolean(v.get());
741      if (isInherited("debugMarshalling"))
742         return restContext().isDebugMarshalling();
743      return false;
744   });
745
746   /**
747    * Whether this operation opts into per-request virtual-thread dispatch on Java 21+.
748    *
749    * <p>
750    * Tri-state semantics on {@code @RestOp}-group annotations: {@code "true"} enables, {@code "false"} disables
751    * (overrides an opted-in resource), and {@code ""} (default) inherits from {@code @Rest(virtualThreads)}. Honored
752    * only when the resource-level {@link RestContext#getVirtualThreadExecutor()} is non-{@code null} (Java 21+).
753    */
754   private final Memoizer<Boolean> virtualThreadsEnabled = memoizer(() -> {
755      var v = findOpString("virtualThreads");
756      if (v.isPresent())
757         return Boolean.parseBoolean(v.get());
758      if (isInherited("virtualThreads"))
759         return restContext().isVirtualThreadsEnabled();
760      return false;
761   });
762
763   /**
764    * Configurable async-response timeout (milliseconds) for this operation; {@code -1} when neither the op
765    * annotation nor the resource declares a value (so {@code AsyncResponseProcessor}'s 30-second default applies).
766    */
767   private final Memoizer<Long> asyncTimeoutMillis = memoizer(() -> {
768      var v = findOpString("asyncTimeoutMillis");
769      if (v.isPresent()) {
770         try {
771            return Long.parseLong(v.get().trim());
772         } catch (NumberFormatException nfe) {
773            return -1L;
774         }
775      }
776      if (isInherited("asyncTimeoutMillis"))
777         return restContext().getAsyncTimeoutMillis();
778      return -1L;
779   });
780
781   /**
782    * Per-op async-completion executor: op-level bean name overrides {@code @Rest}-level, then both are
783    * resolved against the resource's bean store. {@code null} when unset (natural completion thread).
784    */
785   private final Memoizer<Executor> asyncCompletionExecutor = memoizer(() -> {
786      var v = findOpString("asyncCompletionExecutor");
787      if (v.isPresent()) {
788         var name = v.get();
789         var bs = beanStore();
790         var resolved = bs.getBean(Executor.class, name);
791         if (resolved.isEmpty())
792            resolved = bs.getBean(ExecutorService.class, name).map(e -> (Executor) e);
793         if (resolved.isEmpty())
794            throw new IllegalStateException(
795               "@RestOp(asyncCompletionExecutor) on " + restContext().getResourceClass().getName()
796                  + "#" + method().getName() + " references bean name '" + name + "' but no Executor"
797                  + " (or ExecutorService) bean with that name is registered in the resource's bean store.");
798         return resolved.get();
799      }
800      if (isInherited("asyncCompletionExecutor"))
801         return restContext().getAsyncCompletionExecutor();
802      return null;
803   });
804
805   /**
806    * Effective per-op observability state, resolving verb / {@code @RestOp} annotation override first,
807    * then falling back to the resource-level {@code @Rest(observability)} attribute.
808    *
809    * <ul class='values'>
810    *    <li>{@code "true"} &mdash; strict opt-in; this operation requires a wired backend.
811    *    <li>{@code "false"} &mdash; explicit opt-out; the observability block is short-circuited.
812    *    <li>{@code null} &mdash; default inherit behavior; a missing backend silently falls back to NoOp.
813    * </ul>
814    */
815   private final Memoizer<String> observabilityAttr = memoizer(() -> {
816      var v = findOpString("observability");
817      if (v.isPresent())
818         return v.get();
819      if (isInherited("observability"))
820         return restContext().getObservabilityAttribute();
821      return null;
822   });
823
824   /**
825    * Per-op metric name override from {@code @RestOp(metricName)}.
826    * Empty string (default) means the recorder uses its own default name derivation.
827    */
828   private final Memoizer<String> metricName = memoizer(() ->
829      findOpString("metricName").orElse(""));
830
831   /**
832    * Per-op additional metric tags from {@code @RestOp(metricTags)}.
833    * Format: comma-separated {@code key=value} pairs. Empty string (default) means no additional tags.
834    */
835   private final Memoizer<String> metricTags = memoizer(() ->
836      findOpString("metricTags").orElse(""));
837
838   /** Aggregated {@code noInherit} keys from all RestOp-group annotations on this operation. */
839   private final Memoizer<SortedSet<String>> noInheritOp = memoizer(() -> {
840      var l = getRestOpAnnotations().stream()
841         .map(ai -> ai.getStringArray("noInherit").orElse(StringUtils.EMPTY_STRING_ARRAY))
842         .flatMap(this::resolveCdl)
843         .toList();
844      return u(treeSetCi(l));
845   });
846
847   /** The optional (non-required) matchers extracted from {@link #matchersList}. */
848   private final Memoizer<RestMatcher[]> optionalMatchers = memoizer(() -> matchersList.get().getOptionalEntries());
849
850   /** The invokers for context-level post-call lifecycle methods. */
851   private final Memoizer<RestOpInvoker[]> postCallMethods = memoizer(() ->
852      restContext().getPostCallMethods().stream().map(x -> new RestOpInvoker(x, restContext().findRestOperationArgs(x, opBeanStore()), restContext().getMethodExecStats(x), this::resource)).toArray(RestOpInvoker[]::new)
853   );
854
855   /** The invokers for context-level pre-call lifecycle methods. */
856   private final Memoizer<RestOpInvoker[]> preCallMethods = memoizer(() ->
857      restContext().getPreCallMethods().stream().map(x -> new RestOpInvoker(x, restContext().findRestOperationArgs(x, opBeanStore()), restContext().getMethodExecStats(x), this::resource)).toArray(RestOpInvoker[]::new)
858   );
859
860   /**
861    * The parser group for this operation.
862    *
863    * <p>
864    * Walks the {@code @RestOp(parsers)} chain (parent-to-child); the most-derived non-empty
865    * {@code parsers()} array REPLACES the entire inherited set. Falls through to the class-level
866    * {@link RestContext#getParsers()} when no op annotation declares parsers. An
867    * {@code @Bean ParserSet} bean (matching this operation's method scope) REPLACES the result.
868    */
869   private final Memoizer<ParserSet> parsers = memoizer(() -> {
870      var aa = appliedAnnotations();
871      var bs = beanStore();
872      var pb = restContext().getParsersBuilder();
873      var b = pb.copy();
874      if (pb.canApply(aa))
875         b.apply(aa);
876      getRestOpAnnotationsForProperty("parsers").forEach(ai -> {
877         var c = ai.getClassArray("parsers", Object.class).orElse(null);
878         if (nn(c) && c.length > 0)
879            b.set(c);
880      });
881      var result = Holder.of(b.build());
882      bs.createBeanFromMethod(ParserSet.class, resource(), this::matchesInjectScope)
883         .ifPresent(result::set);
884      return result.get();
885   });
886
887   /** The HTTP part parser for this operation (op-level creator applied on top of the parent). */
888   private final Memoizer<HttpPartParser> partParser = memoizer(() -> {
889      var aa = appliedAnnotations();
890      var parent = restContext().getPartParserCreator();
891      if (!parent.canApply(aa))
892         return restContext().getPartParser();
893      Holder<HttpPartParser.Creator> v = Holder.of(parent.copy());
894      v.get().apply(aa);
895      var bs = new BasicBeanStore(beanStore())
896         .addBean(Method.class, method())
897         .addBean(HttpPartParser.Creator.class, v.get());
898      bs.createBeanFromMethod(HttpPartParser.class, resource(), this::matchesInjectScope)
899         .ifPresent(x -> v.get().impl(x));
900      return v.get().create();
901   });
902
903   /** The HTTP part serializer for this operation (op-level creator applied on top of the parent). */
904   private final Memoizer<HttpPartSerializer> partSerializer = memoizer(() -> {
905      var aa = appliedAnnotations();
906      var parent = restContext().getPartSerializerCreator();
907      if (!parent.canApply(aa))
908         return restContext().getPartSerializer();
909      Holder<HttpPartSerializer.Creator> v = Holder.of(parent.copy());
910      v.get().apply(aa);
911      var bs = new BasicBeanStore(beanStore())
912         .addBean(Method.class, method())
913         .addBean(HttpPartSerializer.Creator.class, v.get());
914      bs.createBeanFromMethod(HttpPartSerializer.class, resource(), this::matchesInjectScope)
915         .ifPresent(x -> v.get().impl(x));
916      return v.get().create();
917   });
918
919   /**
920    * The URL path matchers for this operation.
921    *
922    * <p>
923    * Walks the {@code @RestOp}/verb annotation chain (parent-to-child) and collects each
924    * annotation's {@code path[]} array plus its {@code value()} (the conventional shortcut form on
925    * {@link RestGet @RestGet}/{@link RestPost @RestPost}/etc., or the {@code "METHOD path"} pair on
926    * {@link RestOp @RestOp}). When no explicit paths are declared, the operation method name (with
927    * the verb prefix stripped where applicable) is auto-detected via {@link HttpUtils#detectHttpPath}.
928    * For RRPC operations with no explicit path, a trailing {@code "/*"} is appended so the matcher
929    * matches anything below the method's URL.
930    * {@code noInherit={"path"}} cuts off any further parent-chain contribution. A
931    * {@code @Bean UrlPathMatcherList} bean (matching this operation's method scope) REPLACES
932    * the entire result.
933    *
934    * <p>
935    * SVL variables (e.g. {@code ${S:key:default}} or the shorthand {@code ${key:default}}) in path
936    * strings are resolved via the host {@link RestContext}'s {@link VarResolver} before being
937    * compiled into {@link UrlPathMatcher} patterns &mdash; this closes the asymmetry with class-level
938    * {@link Rest#path() @Rest(path)} / {@link Rest#paths() @Rest(paths)}, which are also
939    * SVL-resolved. Strings that contain no SVL markers pass through unchanged, so this is a strict
940    * superset of the previous behavior. Path strings whose entire SVL resolution yields an empty
941    * string are skipped (matching how empty pieces are dropped from the post-comma-split pipeline at
942    * the class level &mdash; see {@code RestContext#splitPathsValue}). Unresolved variables (no
943    * registered {@link Var}) pass through to {@link UrlPathMatcher#of} as the literal {@code ${...}}
944    * placeholder, which then fails predictably at routing time. The auto-detected fallback path
945    * (derived from the method name via {@link HttpUtils#detectHttpPath}) is intentionally
946    * <i>not</i> SVL-resolved &mdash; it is framework-derived, not user input.
947    */
948   private final Memoizer<UrlPathMatcher[]> pathMatchers = memoizer(() -> {
949      var v = Holder.of(UrlPathMatcherList.create());
950      var vr = varResolver();
951      // Use a single VarResolverSession + explicit compile(...) / .resolve(session) per path
952      // so the framework hot path exercises the compiled-template seam explicitly.
953      // Each distinct path string is tokenized once into a VarTemplate, then resolved against
954      // this session. If we ever switch to per-request dynamic path resolution, the seam is
955      // already in place — only the .resolve(session) call moves to the request handler.
956      var session = vr.createSession();
957      getRestOpAnnotationsForProperty("path").forEach(ai -> {
958         for (var p : ai.getStringArray("path").orElse(StringUtils.EMPTY_STRING_ARRAY)) {
959            var resolved = vr.compile(p).resolve(session);
960            if (!resolved.isEmpty())
961               v.get().add(UrlPathMatcher.of(resolved));
962         }
963         // On verb annotations (@RestGet/@RestPost/etc.) value() is always the path. On @RestOp,
964         // value() is "[METHOD] [path]" where the leading method token is optional — only when a
965         // space is present does the trailing token represent a path. To keep this loop annotation-
966         // agnostic, we apply the @RestOp space-split rule only when an @RestOp annotation is in
967         // play (i.e. the annotation type matches), and otherwise treat value() as a plain path.
968         // SVL is applied AFTER the space-split rule so a resolved path can never be misinterpreted
969         // as a "METHOD path" pair (the method token is structural, not user-overridable via SVL).
970         ai.getString("value").filter(StringUtils::isNotBlank).map(String::trim).ifPresent(s -> {
971            if (ai.inner() instanceof RestOp) {
972               var i = s.indexOf(' ');
973               if (i != -1) {
974                  var resolved = vr.compile(s.substring(i).trim()).resolve(session);
975                  if (!resolved.isEmpty())
976                     v.get().add(UrlPathMatcher.of(resolved));
977               }
978            } else {
979               var resolved = vr.compile(s).resolve(session);
980               if (!resolved.isEmpty())
981                  v.get().add(UrlPathMatcher.of(resolved));
982            }
983         });
984      });
985
986      if (v.get().isEmpty()) {
987         var methodInfo2 = MethodInfo.of(method());
988         String httpMethod2 = null;
989         if (methodInfo2.hasAnnotation(RestGet.class))
990            httpMethod2 = "get";
991         else if (methodInfo2.hasAnnotation(RestPut.class))
992            httpMethod2 = "put";
993         else if (methodInfo2.hasAnnotation(RestPost.class))
994            httpMethod2 = "post";
995         else if (methodInfo2.hasAnnotation(RestDelete.class))
996            httpMethod2 = "delete";
997         else if (methodInfo2.hasAnnotation(RestOp.class)) {
998            // @formatter:off
999            httpMethod2 = AP.find(RestOp.class, methodInfo2)
1000               .stream()
1001               .map(x -> x.inner().method())
1002               .filter(Shorts::ine)
1003               .findFirst()
1004               .orElse(null);
1005            // @formatter:on
1006         }
1007
1008         var p = HttpUtils.detectHttpPath(method(), httpMethod2);
1009
1010         // RRPC operations match anything below the method's URL when no explicit path is supplied
1011         if (eqic("RRPC", httpMethod2) && ! p.endsWith("/*"))
1012            p += "/*";
1013
1014         v.get().add(UrlPathMatcher.of(p));
1015      }
1016
1017      beanStore().createBeanFromMethod(UrlPathMatcherList.class, resource(), this::matchesInjectScope, v.get())
1018         .ifPresent(v::set);
1019
1020      // @Mixin(path/paths) re-mount: when this op belongs to a mixin sub-context whose host @Mixin declared a
1021      // mount prefix, re-mount every matcher under each host-chosen prefix.  Reuses the pathToken normalization
1022      // (via RestContext.getMixinMountPrefixes) so override input forms (bare / leading-slash / trailing /*)
1023      // all collapse to one clean prefix.  Build-time only.
1024      var prefixes = restContext().getMixinMountPrefixes();
1025      if (! prefixes.isEmpty()) {
1026         var remounted = UrlPathMatcherList.create();
1027         for (var prefix : prefixes)
1028            for (var pm : v.get().asArray())
1029               remounted.add(UrlPathMatcher.of(prefixPath(prefix, pm.toString())));
1030         v.set(remounted);
1031      }
1032
1033      return v.get().asArray();
1034   });
1035
1036   /**
1037    * Prepends a host-chosen mixin mount prefix to an op path pattern.
1038    *
1039    * <p>
1040    * {@code prefix} is a bare token (no slashes — already normalized by {@code RestContext.getMixinMountPrefixes}).
1041    * The original pattern keeps its leading slash and any trailing {@code /*}; e.g. prefix {@code "admin"} +
1042    * pattern {@code /info} &rarr; {@code /admin/info}, and prefix {@code "admin"} + {@code /loggers/*} &rarr;
1043    * {@code /admin/loggers/*}.
1044    *
1045    * @param prefix The normalized mount-prefix token.
1046    * @param pattern The original op path pattern.
1047    * @return The prefixed pattern.
1048    */
1049   private static String prefixPath(String prefix, String pattern) {
1050      var p = pattern.startsWith("/") ? pattern : "/" + pattern;
1051      return "/" + prefix + p;
1052   }
1053
1054   /** The required matchers extracted from {@link #matchersList}. */
1055   private final Memoizer<RestMatcher[]> requiredMatchers = memoizer(() -> matchersList.get().getRequiredEntries());
1056
1057   // Immutable, cached views over the routing arrays returned by the public getters.  Built once (memoized) so
1058   // there is zero per-call allocation on the routing hot path and no live-array exposure to callers.  Internal
1059   // hot-path code reads the private array memoizers directly; these views exist only for the public API surface.
1060   private final Memoizer<List<UrlPathMatcher>> pathMatchersView = memoizer(() -> List.of(pathMatchers.get()));
1061   private final Memoizer<List<RestMatcher>> optionalMatchersView = memoizer(() -> List.of(optionalMatchers.get()));
1062   private final Memoizer<List<RestMatcher>> requiredMatchersView = memoizer(() -> List.of(requiredMatchers.get()));
1063
1064   /** The computed response metadata for this operation method. */
1065   private final Memoizer<ResponseBeanMeta> responseMeta = memoizer(() -> ResponseBeanMeta.create(methodInfo(), appliedAnnotations()));
1066
1067   /**
1068    * All {@link RestOp}-group annotations on this method, in child-to-parent order.
1069    *
1070    * <p>
1071    * Uses the same {@link MethodInfo} as the annotation traversal in the {@link Builder}, so
1072    * method-level metadata (e.g. {@code noInherit}) resolves consistently when the implementation
1073    * class differs from the method's declaring class.
1074    */
1075   private final Memoizer<List<AnnotationInfo<?>>> restOpAnnotations = memoizer(() -> {
1076      var methodInfo = MethodInfo.of(restContext().getResourceClass(), method()).accessible();
1077      return restContext().getAnnotationProvider().find(methodInfo, SELF, MATCHING_METHODS).stream()
1078         .filter(ai -> ai.isInGroup(RestOp.class))
1079         .toList();
1080   });
1081
1082   /**
1083    * The serializer group for this operation.
1084    *
1085    * <p>
1086    * Walks the {@code @RestOp(serializers)} chain (parent-to-child); the most-derived non-empty
1087    * {@code serializers()} array REPLACES the entire inherited set. Falls through to the class-level
1088    * {@link RestContext#getSerializers()} when no op annotation declares serializers. An
1089    * {@code @Bean SerializerSet} bean (matching this operation's method scope) REPLACES the result.
1090    */
1091   private final Memoizer<SerializerSet> serializers = memoizer(() -> {
1092      var aa = appliedAnnotations();
1093      var bs = beanStore();
1094      var sb = restContext().getSerializersBuilder();
1095      var b = sb.copy();
1096      if (sb.canApply(aa))
1097         b.apply(aa);
1098      getRestOpAnnotationsForProperty("serializers").forEach(ai -> {
1099         var c = ai.getClassArray("serializers", Serializer.class).orElse(null);
1100         if (nn(c) && c.length > 0)
1101            b.set(c);
1102      });
1103      var result = Holder.of(b.build());
1104      bs.createBeanFromMethod(SerializerSet.class, resource(), this::matchesInjectScope)
1105         .ifPresent(result::set);
1106      return result.get();
1107   });
1108
1109   /**
1110    * The supported response accept types for this operation.
1111    *
1112    * <p>
1113    * Walks op-level {@code @RestOp}-group annotations for {@code produces} (and, when
1114    * {@code noInherit} does not block it, the class-level {@code @Rest(produces)} hierarchy).
1115    * Falls back to the supported media types of the operation's {@link SerializerSet}.
1116    */
1117   private final Memoizer<List<MediaType>> supportedAcceptTypes = memoizer(() -> {
1118      var result = collectAnnotationMediaTypes("produces");
1119      if (result.isEmpty())
1120         return u(getSerializers().getSupportedMediaTypes());
1121      return u(result);
1122   });
1123
1124   /**
1125    * The supported request content types for this operation.
1126    *
1127    * <p>
1128    * Walks op-level {@code @RestOp}-group annotations for {@code consumes} (and, when
1129    * {@code noInherit} does not block it, the class-level {@code @Rest(consumes)} hierarchy).
1130    * Falls back to the supported content types of the operation's {@link ParserSet}.
1131    */
1132   private final Memoizer<List<MediaType>> supportedContentTypes = memoizer(() -> {
1133      var result = collectAnnotationMediaTypes("consumes");
1134      if (result.isEmpty())
1135         return u(getParsers().getSupportedMediaTypes());
1136      return u(result);
1137   });
1138
1139   /**
1140    * Iterates over each parameter annotation on the operation method, computing the parameter's
1141    * {@link Schema#default_()}/{@link Schema#df()} string (joined-non-blank-first) and dispatching
1142    * each annotation+default pair to the supplied callback.
1143    */
1144   private void processParameterDefaults(BiConsumer<Annotation,String> callback) {
1145      for (var aa : method.getParameterAnnotations()) {
1146         String def = null;
1147         for (var a : aa) {
1148            if (a instanceof Schema a2)
1149               def = joinnlFirstNonEmptyArray(a2.default_(), a2.df());
1150         }
1151         if (def == null)
1152            continue;
1153         for (var a : aa)
1154            callback.accept(a, def);
1155      }
1156   }
1157
1158   /**
1159    * Returns {@code true} if the given method has a {@code @Bean} annotation whose
1160    * {@code methodScope} includes this operation's method name (or {@code "*"}).
1161    *
1162    * <p>
1163    * Used by op-level memoizers when scanning the resource class for {@code @Bean}-supplied
1164    * composite-bean overrides ({@code RestConverterList}, {@code RestGuardList}, etc.). This is the
1165    * {@link RestOpContext}-scope peer of {@link Builder#matches(MethodInfo)} — kept in sync with that
1166    * one.
1167    */
1168   private boolean matchesInjectScope(MethodInfo annotated) {
1169      var a = annotated.getAnnotations(Bean.class).findFirst().map(AnnotationInfo::inner).orElse(null);
1170      if (a != null) {
1171         for (var n : a.methodScope()) {
1172            if (eq(n, "*") || method.getName().equals(n))
1173               return true;
1174         }
1175      }
1176      return false;
1177   }
1178
1179   /**
1180    * Same as {@link #matchesInjectScope(MethodInfo)} but additionally requires the
1181    * {@link Bean#name()} attribute to equal {@code beanName}.
1182    *
1183    * <p>
1184    * Used for named composite-bean overrides ({@code defaultRequestHeaders}, {@code defaultResponseHeaders},
1185    * etc.) where the bean type alone is ambiguous (e.g. {@link HeaderList} appears as both request and
1186    * response headers).
1187    */
1188   private boolean matchesInjectScope(MethodInfo annotated, String beanName) {
1189      var a = annotated.getAnnotations(Bean.class).findFirst().map(AnnotationInfo::inner).orElse(null);
1190      if (a != null) {
1191         if (! BeanAnnotation.name(a).equals(beanName))
1192            return false;
1193         for (var n : a.methodScope()) {
1194            if (eq(n, "*") || method.getName().equals(n))
1195               return true;
1196         }
1197      }
1198      return false;
1199   }
1200
1201   private Stream<String> resolveCdl(String...values) {
1202      if (values == null || values.length == 0)
1203         return Stream.empty();
1204      return Arrays.stream(values)
1205         .filter(Objects::nonNull)
1206         .map(s -> context.getVarResolver().resolve(s))
1207         .map(StringUtils::split)
1208         .flatMap(Collection::stream)
1209         .map(String::trim)
1210         .filter(StringUtils::isNotBlank);
1211   }
1212
1213   /**
1214    * Returns all {@link RestOp}-group annotations on this operation method, in child-to-parent order.
1215    *
1216    * @return An unmodifiable list, never {@code null}.
1217    */
1218   public List<AnnotationInfo<?>> getRestOpAnnotations() {
1219      return restOpAnnotations.get();
1220   }
1221
1222   /**
1223    * Returns the {@link RestOp}-group annotations on this method for the specified property,
1224    * in <b>parent-to-child</b> order, with op-level {@code noInherit} cutoff applied.
1225    *
1226    * <p>
1227    * Mirrors {@link RestContext#getRestAnnotationsForProperty(String)} but for the op-level chain. Used by
1228    * op-level memoizers ({@link #converters}, {@link #guards}, {@link #matchersList},
1229    * {@link #encoders}, etc.) when accumulating values from each {@code @RestOp} / {@code @RestGet} /
1230    * {@code @RestPut} / {@code @RestPost} / {@code @RestDelete} / {@code @RestPatch} / {@code @RestOptions}
1231    * annotation in the method-override chain.
1232    *
1233    * @param name The annotation property name (e.g. {@code "converters"}, {@code "guards"}).
1234    * @return A stream of {@link AnnotationInfo} entries in parent-to-child order, never {@code null}.
1235    */
1236   Stream<AnnotationInfo<?>> getRestOpAnnotationsForProperty(String name) {
1237      var annotations = getRestOpAnnotations();
1238      var cutoff = annotations.size();
1239      for (var i = 0; i < annotations.size(); i++) {
1240         if (resolveCdl(annotations.get(i).getStringArray("noInherit").orElse(StringUtils.EMPTY_STRING_ARRAY)).anyMatch(name::equalsIgnoreCase)) {
1241            cutoff = i + 1;
1242            break;
1243         }
1244      }
1245      return rstream(annotations.subList(0, cutoff));
1246   }
1247
1248   /**
1249    * Returns {@code true} if context-level values for the given property should be merged.
1250    *
1251    * @param property The annotation attribute name (e.g. {@code "allowedParserOptions"},
1252    *    {@code "defaultCharset"}, {@code "maxInput"}).
1253    * @return {@code true} if {@code noInherit} does not contain this property.
1254    */
1255   protected boolean isInherited(String property) {
1256      return !noInheritOp.get().contains(property);
1257   }
1258
1259   /**
1260    * Returns the parser session-option keys allowed for this operation.
1261    *
1262    * @return An unmodifiable case-insensitive sorted set, never {@code null}.
1263    */
1264   public SortedSet<String> getAllowedParserOptions() {
1265      return allowedParserOptions.get();
1266   }
1267
1268   /**
1269    * Returns the serializer session-option keys allowed for this operation.
1270    *
1271    * @return An unmodifiable case-insensitive sorted set, never {@code null}.
1272    */
1273   public SortedSet<String> getAllowedSerializerOptions() {
1274      return allowedSerializerOptions.get();
1275   }
1276
1277   /**
1278    * Startup-fail: validates that when the effective observability attribute for this op is {@code "true"},
1279    * at least one real backend ({@link org.apache.juneau.rest.server.metrics.MetricsRecorder} or
1280    * {@link org.apache.juneau.rest.server.tracing.TracerHook}) is registered.
1281    *
1282    * <p>
1283    * Called once during construction.  The resource-level check in {@link RestContext#checkObservabilityBackendPresent()}
1284    * already fires for {@code @Rest(observability="true")}; this companion fires for individual
1285    * {@code @RestOp(observability="true")} overrides that elevate a single op into strict mode.
1286    */
1287   private void checkOpObservabilityBackendPresent() {
1288      var attr = observabilityAttr.get();
1289      if (neqic("true", attr))
1290         return;
1291      var bs = beanStore();
1292      var recorder = bs.getBean(org.apache.juneau.rest.server.metrics.MetricsRecorder.class).orElse(null);
1293      var tracer = bs.getBean(org.apache.juneau.rest.server.tracing.TracerHook.class).orElse(null);
1294      boolean hasRecorder = recorder != null && !(recorder instanceof org.apache.juneau.rest.server.metrics.NoOpMetricsRecorder);
1295      boolean hasTracer = tracer != null && !(tracer instanceof org.apache.juneau.rest.server.tracing.NoOpTracerHook);
1296      if (!hasRecorder && !hasTracer)
1297         throw new InternalServerError(
1298            "@RestOp(observability=\"true\") is set on " + context.getResourceClass().getSimpleName() + "." + method.getName()
1299            + " but no MetricsRecorder or TracerHook @Bean is registered. "
1300            + "Either wire a backend or change observability to \"\" (inherit) or \"false\" (opt-out).");
1301   }
1302
1303   /**
1304    * Returns the first non-blank, SVL-resolved value of the given attribute across all
1305    * {@code @RestOp}-group annotations on this method (child-to-parent order).
1306    *
1307    * @param attr The annotation attribute name (e.g. {@code "defaultCharset"}).
1308    * @return The resolved string, or empty if no annotation defines it.
1309    */
1310   private Optional<String> findOpString(String attr) {
1311      var vr = varResolver();
1312      for (var ai : getRestOpAnnotations()) {
1313         var s = ai.getString(attr).orElse("");
1314         if (!s.isEmpty()) {
1315            var resolved = vr.resolve(s);
1316            if (!resolved.isEmpty())
1317               return o(resolved);
1318         }
1319      }
1320      return oe();
1321   }
1322
1323   private List<MediaType> collectAnnotationMediaTypes(String attr) {
1324      var result = new ArrayList<MediaType>();
1325      var vr = varResolver();
1326      // Class-level @Rest(consumes|produces) first (when inheritance is allowed), then op-level overrides append.
1327      if (isInherited(attr)) {
1328         for (var ai : restContext().getRestAnnotations())
1329            appendResolvedMediaTypes(ai, attr, vr, result);
1330      }
1331      for (var ai : getRestOpAnnotations())
1332         appendResolvedMediaTypes(ai, attr, vr, result);
1333      return result;
1334   }
1335
1336   private static void appendResolvedMediaTypes(AnnotationInfo<?> ai, String attr, VarResolver vr, List<MediaType> result) {
1337      var arr = ai.getStringArray(attr).orElse(null);
1338      if (arr == null)
1339         return;
1340      for (var s : arr) {
1341         if (isNotEmpty(s)) {
1342            var resolved = vr.resolve(s);
1343            if (!resolved.isEmpty())
1344               result.add(MediaType.of(resolved));
1345         }
1346      }
1347   }
1348
1349   private static String httpMethodFromAnnotation(Annotation a, VarResolver vr) {
1350      if (a instanceof RestGet)
1351         return "get";
1352      if (a instanceof RestPut)
1353         return "put";
1354      if (a instanceof RestPost)
1355         return "post";
1356      if (a instanceof RestDelete)
1357         return "delete";
1358      if (a instanceof RestPatch)
1359         return "patch";
1360      if (a instanceof RestOptions)
1361         return "options";
1362      if (a instanceof RestOp a2) {
1363         var m = vr.resolve(a2.method());
1364         if (ine(m))
1365            return m;
1366         var s = vr.resolve(a2.value());
1367         if (s != null) {
1368            s = s.trim();
1369            if (!s.isEmpty()) {
1370               var i = s.indexOf(' ');
1371               return i == -1 ? s : s.substring(0, i).trim();
1372            }
1373         }
1374      }
1375      return null;
1376   }
1377
1378   private static String normalizeHttpMethod(String v) {
1379      if (eqic("METHOD", v))
1380         return "*";
1381      return ucr(v);
1382   }
1383
1384   /**
1385    * 2-arg positional context constructor.
1386    *
1387    * <p>
1388    * All operation-level configuration is resolved from {@link RestOp}-group annotations on the method and
1389    * inherited from the parent {@link RestContext}.
1390    *
1391    * @param method The Java method this context represents. Must not be <jk>null</jk>.
1392    * @param context The owning {@link RestContext}. Must not be <jk>null</jk>.
1393    * @throws ServletException If context could not be created.
1394    * @since 9.2.1
1395    */
1396   public RestOpContext(java.lang.reflect.Method method, RestContext context) throws ServletException {
1397      this(new Builder(method, context));
1398   }
1399
1400   /**
1401    * 3-arg positional context constructor.
1402    *
1403    * @param method The Java method this context represents. Must not be <jk>null</jk>.
1404    * @param context The owning {@link RestContext}. Must not be <jk>null</jk>.
1405    * @param resourceSupplier Supplier that returns the invocation target for this operation.
1406    * @throws ServletException If context could not be created.
1407    */
1408   public RestOpContext(java.lang.reflect.Method method, RestContext context, Supplier<Object> resourceSupplier) throws ServletException {
1409      this(new Builder(method, context, resourceSupplier));
1410   }
1411
1412   /**
1413    * Context constructor.
1414    *
1415    * @param builder The builder for this object.
1416    * @throws ServletException If context could not be created.
1417    */
1418   private RestOpContext(Builder builder) throws ServletException {
1419      super(builder);
1420
1421      try {
1422         // Capture the annotation work-list before the builder becomes eligible for GC.
1423         appliedAnnotations = builder.getApplied();
1424
1425         context = builder.restContext;
1426         method = builder.restMethod;
1427         resourceSupplier = builder.restResourceSupplier;
1428
1429         mi = MethodInfo.of(method).accessible();
1430
1431         var bs = new BasicBeanStore(context.getBootstrapBeanStore());
1432         bs.addBean(RestOpContext.class, this);
1433         bs.addBean(Method.class, method);
1434         bs.addBean(AnnotationWorkList.class, appliedAnnotations);
1435         opBeanStore = bs;
1436
1437         bs.add(MarshallingContext.class, getMarshallingContext());
1438         bs.add(RestConverter[].class, getConverters());
1439         bs.add(EncoderSet.class, getEncoders());
1440         bs.add(RestGuard[].class, getGuards());
1441         bs.add(JsonSchemaGenerator.class, getJsonSchemaGenerator());
1442         bs.add(ParserSet.class, getParsers());
1443         bs.add(HttpPartParser.class, getPartParser());
1444         bs.add(HttpPartSerializer.class, getPartSerializer());
1445         bs.add(SerializerSet.class, getSerializers());
1446
1447      // Inject @Value-annotated env-driven defaults onto this RestOpContext instance so that the
1448      // memoizer lambdas (defaultCharset, maxInput) read fully resolved values when first invoked.
1449      ClassInfo.of(this).inject(this, bs);
1450
1451      // Startup-fail check: if this op (or its resource) declares observability="true" but neither
1452      // MetricsRecorder nor TracerHook is wired, fail fast with a precise error.
1453      checkOpObservabilityBackendPresent();
1454
1455      // The 6 formerly-eager scalar fields are now memoized; no eagerness needed here.
1456      // Pre-warm httpMethod so it is in the memoizer cache for immediate use by compareTo/match.
1457      httpMethod.get();
1458
1459      // Fail servlet init (not the first request) if a concrete @Request bean parameter has a getter with no matching
1460      // setter or no public no-arg constructor; the arg is rebuilt lazily with the invoker.
1461      for (var pi : mi.getParameters())
1462         org.apache.juneau.rest.server.arg.RequestBeanArg.create(pi, appliedAnnotations);
1463
1464         var pm = pathMatchers.get();
1465         bs.add(UrlPathMatcher[].class, pm);
1466         bs.addBean(UrlPathMatcher.class, pm.length > 0 ? pm[0] : null);
1467
1468      } catch (Exception e) {
1469         throw new ServletException(e);
1470      }
1471   }
1472
1473   /*
1474    * compareTo() method is used to keep SimpleMethods ordered in the RestCallRouter list.
1475    * It maintains the order in which matches are made during requests.
1476    */
1477   @Override /* Overridden from Comparable */
1478   public int compareTo(RestOpContext o) {
1479      int c;
1480
1481      var pm = pathMatchers.get();
1482      var opm = o.pathMatchers.get();
1483      for (int i = 0; i < Math.min(pm.length, opm.length); i++) {
1484         c = pm[i].compareTo(opm[i]);
1485         if (c != 0)
1486            return c;
1487      }
1488
1489      c = cmp(o.hierarchyDepth.get(), hierarchyDepth.get());
1490      if (c != 0)
1491         return c;
1492
1493      c = cmp(o.requiredMatchers.get().length, requiredMatchers.get().length);
1494      if (c != 0)
1495         return c;
1496
1497      c = cmp(o.optionalMatchers.get().length, optionalMatchers.get().length);
1498      if (c != 0)
1499         return c;
1500
1501      c = cmp(o.getGuards().length, getGuards().length);
1502
1503      if (c != 0)
1504         return c;
1505
1506      c = cmp(method.getName(), o.method.getName());
1507      if (c != 0)
1508         return c;
1509
1510      c = cmp(method.getParameterCount(), o.method.getParameterCount());
1511      if (c != 0)
1512         return c;
1513
1514      for (var i = 0; i < method.getParameterCount(); i++) {
1515         c = cmp(method.getParameterTypes()[i].getName(), o.method.getParameterTypes()[i].getName());
1516         if (c != 0)
1517            return c;
1518      }
1519
1520      c = cmp(method.getReturnType().getName(), o.method.getReturnType().getName());
1521      if (c != 0)
1522         return c;
1523
1524      // Declaring-class tie-breaker: keeps compareTo consistent with equals()/hashCode() (which key off method
1525      // identity) for two ops whose methods share the same signature but differ by declaring class.  Only affects
1526      // ordering that was previously a zero-tie, so it makes tie-break stability deterministic rather than changing
1527      // any non-tied dispatch precedence.
1528      c = cmp(method.getDeclaringClass().getName(), o.method.getDeclaringClass().getName());
1529      if (c != 0)
1530         return c;
1531
1532      return 0;
1533   }
1534
1535   @Override /* Overridden from Context */
1536   public Context.Builder copy() {
1537      throw uoex();
1538   }
1539
1540   /**
1541    * Creates a {@link RestRequest} object based on the specified incoming {@link HttpServletRequest} object.
1542    *
1543    * @param session The current REST call.
1544    * @return The wrapped request object.
1545    * @throws Exception If any errors occur trying to interpret the request.
1546    */
1547   public RestRequest createRequest(RestSession session) throws Exception {
1548      return new RestRequest(this, session);
1549   }
1550
1551   /**
1552    * Creates a {@link RestResponse} object based on the specified incoming {@link HttpServletResponse} object
1553    * and the request returned by {@link #createRequest(RestSession)}.
1554    *
1555    * @param session The current REST call.
1556    * @param req The REST request.
1557    * @return The wrapped response object.
1558    * @throws Exception If any errors occur trying to interpret the request or response.
1559    */
1560   public RestResponse createResponse(RestSession session, RestRequest req) throws Exception {
1561      return new RestResponse(this, session, req);
1562   }
1563
1564   /**
1565    * Creates a new REST operation session.
1566    *
1567    * @param session The REST session.
1568    * @return A new REST operation session.
1569    * @throws Exception If op session could not be created.
1570    */
1571   public RestOpSession.Builder createSession(RestSession session) throws Exception {
1572      var b = RestOpSession.create(this, session);
1573      if (getLogger().isLoggable(Level.FINEST))
1574         session.installCapture();
1575      return b;
1576   }
1577
1578   @Override /* Overridden from Object */
1579   public boolean equals(Object o) {
1580      return (o instanceof RestOpContext o2) && eq(this, o2, (x, y) -> eq(x.method, y.method));
1581   }
1582
1583   /**
1584    * Returns the marshalling context associated with this context.
1585    *
1586    * @return The marshalling context associated with this context.
1587    */
1588   public MarshallingContext getMarshallingContext() { return marshallingContext.get(); }
1589
1590   /**
1591    * Returns the default charset.
1592    *
1593    * @return The default charset.  Never <jk>null</jk>.
1594    */
1595   public Charset getDefaultCharset() { return defaultCharset.get(); }
1596
1597   /**
1598    * Returns the default request attributes.
1599    *
1600    * @return The default request attributes.  Never <jk>null</jk>.
1601    */
1602   public NamedAttributeMap getDefaultRequestAttributes() { return defaultRequestAttributes.get(); }
1603
1604   /**
1605    * Returns the default form data parameters.
1606    *
1607    * @return The default form data parameters.  Never <jk>null</jk>.
1608    */
1609   public HttpPartList getDefaultRequestFormData() { return defaultRequestFormData.get(); }
1610
1611   /**
1612    * Returns the default request headers.
1613    *
1614    * @return The default request headers.  Never <jk>null</jk>.
1615    */
1616   public HttpHeaderList getDefaultRequestHeaders() { return defaultRequestHeaders.get(); }
1617
1618   /**
1619    * Returns the default request query parameters.
1620    *
1621    * @return The default request query parameters.  Never <jk>null</jk>.
1622    */
1623   public HttpPartList getDefaultRequestQueryData() { return defaultRequestQueryData.get(); }
1624
1625   /**
1626    * Returns the default response headers.
1627    *
1628    * @return The default response headers.  Never <jk>null</jk>.
1629    */
1630   public HttpHeaderList getDefaultResponseHeaders() { return defaultResponseHeaders.get(); }
1631
1632   /**
1633    * Returns the compression encoders to use for this method.
1634    *
1635    * @return The compression encoders to use for this method.
1636    */
1637   public EncoderSet getEncoders() { return encoders.get(); }
1638
1639   /**
1640    * Returns the HTTP method name (e.g. <js>"GET"</js>).
1641    *
1642    * @return The HTTP method name.
1643    */
1644   public String getHttpMethod() { return httpMethod.get(); }
1645
1646   /**
1647    * Returns whether this operation is declared {@link RestOp#read() read=true}.
1648    *
1649    * <p>
1650    * A read operation may be reached by overriding a safe request (<c>GET</c>, <c>HEAD</c>, <c>OPTIONS</c>,
1651    * <c>TRACE</c>) to its custom method.
1652    *
1653    * @return <jk>true</jk> if this operation is declared a read.
1654    * @throws InternalServerError If <c>read=<jk>true</jk></c> is declared on an inherited <ja>@RestOp</ja> that names
1655    *    no method.
1656    * @since 10.0.0
1657    */
1658   public boolean isRead() { return read.get(); }
1659
1660   /**
1661    * Returns the underlying Java method that this context belongs to.
1662    *
1663    * @return The underlying Java method that this context belongs to.
1664    */
1665   public Method getJavaMethod() { return method; }
1666
1667   /**
1668    * Returns the JSON-Schema generator applicable to this Java method.
1669    *
1670    * @return The JSON-Schema generator applicable to this Java method.
1671    */
1672   public JsonSchemaGenerator getJsonSchemaGenerator() { return jsonSchemaGenerator.get(); }
1673
1674   /**
1675    * Returns the max number of bytes to process in the input content.
1676    *
1677    * @return The max number of bytes to process in the input content.
1678    */
1679   public long getMaxInput() { return maxInput.get(); }
1680
1681   /**
1682    * Returns whether this operation emits RFC 7807 {@code application/problem+json} responses.
1683    *
1684    * <p>
1685    * Tri-state inheritance semantics: an explicit {@code "true"} or {@code "false"} on the operation annotation
1686    * wins; otherwise the value is inherited from {@link RestContext#isProblemDetails()} (resource-level
1687    * {@code @Rest(problemDetails)}).
1688    *
1689    * <h4 class='section'>See Also:</h4><ul>
1690    *    <li class='ja'>{@link Rest#problemDetails()}
1691    *    <li class='ja'>{@link RestOp#problemDetails()}
1692    * </ul>
1693    *
1694    * @return <jk>true</jk> if RFC 7807 problem-details responses are enabled on this operation.
1695    */
1696   public boolean isProblemDetails() { return problemDetails.get(); }
1697
1698   /**
1699    * Returns whether REST-driven serializer/parser debug behavior is enabled for this operation.
1700    *
1701    * <p>
1702    * Resolved via the tri-state {@code @RestOp}-group {@code debugMarshalling} attribute ({@code "true"} wins,
1703    * {@code "false"} opts out, {@code ""} inherits the resource-level {@code @Rest(debugMarshalling)}), independent
1704    * of the JUL logger level.
1705    *
1706    * <h4 class='section'>See Also:</h4><ul>
1707    *    <li class='ja'>{@link Rest#debugMarshalling()}
1708    *    <li class='ja'>{@link RestOp#debugMarshalling()}
1709    * </ul>
1710    *
1711    * @return <jk>true</jk> if REST-driven marshalling debug is enabled for this operation.
1712    */
1713   public boolean isDebugMarshalling() { return debugMarshalling.get(); }
1714
1715   /**
1716    * Returns whether this operation opts into per-request virtual-thread dispatch on Java 21+.
1717    *
1718    * <p>
1719    * The op-level {@code @RestOp(virtualThreads)} value (when non-blank) wins; otherwise the value is inherited
1720    * from {@link RestContext#isVirtualThreadsEnabled()} (resource-level {@code @Rest(virtualThreads)}). Honored
1721    * only when the resource-level {@link RestContext#getVirtualThreadExecutor()} is non-{@code null} (Java 21+).
1722    *
1723    * @return <jk>true</jk> if virtual-thread dispatch is configured on this operation.
1724    */
1725   public boolean isVirtualThreadsEnabled() { return virtualThreadsEnabled.get(); }
1726
1727   /**
1728    * Returns whether the observability block is enabled for this operation.
1729    *
1730    * <p>
1731    * Returns {@code false} when the effective resolved attribute is {@code "false"} (explicit opt-out).
1732    * Returns {@code true} in all other cases ({@code "true"} strict opt-in or empty/null default).
1733    *
1734    * <p>
1735    * Note: the default behavior (empty/null attribute) still runs the observability block, but silently
1736    * falls back to {@link org.apache.juneau.rest.server.metrics.NoOpMetricsRecorder} when no backend is wired.
1737    * Only {@code "false"} completely short-circuits the block.
1738    *
1739    * @return <jk>false</jk> when this operation has explicitly opted out of observability.
1740    * @see RestOp#observability()
1741    * @see Rest#observability()
1742    */
1743   public boolean isObservabilityEnabled() {
1744      var v = observabilityAttr.get();
1745      return neqic("false", v);
1746   }
1747
1748   /**
1749    * Returns the per-op metric name override from {@code @RestOp(metricName)}.
1750    *
1751    * @return The metric name override, or an empty string when not set.
1752    * @see RestOp#metricName()
1753    */
1754   public String getMetricName() { return metricName.get(); }
1755
1756   /**
1757    * Returns the per-op additional metric tags from {@code @RestOp(metricTags)}.
1758    *
1759    * @return The tags string (comma-separated {@code key=value} pairs), or empty string when not set.
1760    * @see RestOp#metricTags()
1761    */
1762   public String getMetricTags() { return metricTags.get(); }
1763
1764   /**
1765    * Returns the configured async-response timeout (milliseconds) for this operation, or {@code -1} when no
1766    * value was supplied at the op or resource level — in which case the default 30-second fallback applies in
1767    * {@link org.apache.juneau.rest.server.processor.AsyncResponseProcessor}.
1768    *
1769    * @return The async timeout in milliseconds, or {@code -1} when unset.
1770    */
1771   public long getAsyncTimeoutMillis() { return asyncTimeoutMillis.get(); }
1772
1773   /**
1774    * Returns the effective {@link Executor} for routing
1775    * {@link CompletableFuture} completion callbacks on this operation, or
1776    * {@code null} when neither the op nor the resource configures an executor (natural completion thread).
1777    *
1778    * @return The executor, or {@code null} if no async-completion executor is configured.
1779    * @since 10.0.0
1780    */
1781   public Executor getAsyncCompletionExecutor() { return asyncCompletionExecutor.get(); }
1782
1783   /**
1784    * Returns the parsers to use for this method.
1785    *
1786    * @return The parsers to use for this method.
1787    */
1788   public ParserSet getParsers() { return parsers.get(); }
1789
1790   /**
1791    * Bean property getter:  <property>partParser</property>.
1792    *
1793    * @return The value of the <property>partParser</property> property on this bean, or <jk>null</jk> if it is not set.
1794    */
1795   public HttpPartParser getPartParser() { return partParser.get(); }
1796
1797   /**
1798    * Bean property getter:  <property>partSerializer</property>.
1799    *
1800    * @return The value of the <property>partSerializer</property> property on this bean, or <jk>null</jk> if it is not set.
1801    */
1802   public HttpPartSerializer getPartSerializer() { return partSerializer.get(); }
1803
1804   /**
1805    * Returns the path pattern for this method.
1806    *
1807    * @return The path pattern.
1808    */
1809   public String getPathPattern() { return pathMatchers.get()[0].toString(); }
1810
1811   /**
1812    * Returns the URL path matchers for this operation.
1813    *
1814    * @return The URL path matchers for this operation.
1815    *    <br>Never <jk>null</jk>.
1816    *    <br>The returned list is an immutable, cached view.
1817    */
1818   public List<UrlPathMatcher> getPathMatchers() { return pathMatchersView.get(); }
1819
1820   /**
1821    * Returns the optional matchers for this operation.
1822    *
1823    * @return The optional matchers for this operation.
1824    *    <br>Never <jk>null</jk>.
1825    *    <br>The returned list is an immutable, cached view.
1826    */
1827   public List<RestMatcher> getOptionalMatchers() { return optionalMatchersView.get(); }
1828
1829   /**
1830    * Returns the required matchers for this operation.
1831    *
1832    * @return The required matchers for this operation.
1833    *    <br>Never <jk>null</jk>.
1834    *    <br>The returned list is an immutable, cached view.
1835    */
1836   public List<RestMatcher> getRequiredMatchers() { return requiredMatchersView.get(); }
1837
1838   /**
1839    * Returns the per-operation logger used for debug capture.
1840    *
1841    * <p>
1842    * A hierarchical child of the host resource's resolved logger ({@code <hostLoggerName>.<methodName>}) &mdash;
1843    * see the {@code logger} memoizer for how the host's bean-store-overridden {@link RichLogger} (if any) is
1844    * honored.
1845    *
1846    * @return The per-operation logger.
1847    *    <br>Never <jk>null</jk>.
1848    */
1849   public RichLogger getLogger() { return logger.get(); }
1850
1851   /**
1852    * Returns metadata about the specified response object if it's annotated with {@link Response @Response}.
1853    *
1854    * @param o The response POJO.  Can be <jk>null</jk> (returns <jk>null</jk>).
1855    * @return Metadata about the specified response object, or <jk>null</jk> if it's not annotated with {@link Response @Response}.
1856    */
1857   public ResponseBeanMeta getResponseBeanMeta(Object o) {
1858      if (o == null)
1859         return null;
1860      var c = o.getClass();
1861      var rbm = responseBeanMetas.get(c);
1862      if (rbm == null) {
1863         rbm = ResponseBeanMeta.create(c, AnnotationWorkList.create());
1864         if (rbm == null)
1865            rbm = ResponseBeanMeta.NULL;
1866         responseBeanMetas.put(c, rbm);
1867      }
1868      if (rbm == ResponseBeanMeta.NULL)
1869         return null;
1870      return rbm;
1871   }
1872
1873   /**
1874    * Returns metadata about the specified response object if it's annotated with {@link Header @Header}.
1875    *
1876    * @param o The response POJO.  Can be <jk>null</jk> (returns <jk>null</jk>).
1877    * @return Metadata about the specified response object, or <jk>null</jk> if it's not annotated with {@link Header @Header}.
1878    */
1879   public ResponsePartMeta getResponseHeaderMeta(Object o) {
1880      if (o == null)
1881         return null;
1882      var c = o.getClass();
1883      var pm = headerPartMetas.get(c);
1884      if (pm == null) {
1885         var a = ClassInfo.of(c).getAnnotations(Header.class).findFirst().map(AnnotationInfo::inner).orElse(null);
1886         if (nn(a)) {
1887            var schema = HttpPartSchema.create(a);
1888         var serializer = createPartSerializer((Class<? extends HttpPartSerializer>)schema.getSerializer(), getPartSerializer());
1889            pm = new ResponsePartMeta(HEADER, schema, serializer);
1890         }
1891         if (pm == null)
1892            pm = ResponsePartMeta.NULL;
1893         headerPartMetas.put(c, pm);
1894      }
1895      if (pm == ResponsePartMeta.NULL)
1896         return null;
1897      return pm;
1898   }
1899
1900   /**
1901    * Returns the response bean meta if this method returns a {@link Response}-annotated bean.
1902    *
1903    * @return The response bean meta or <jk>null</jk> if it's not a {@link Response}-annotated bean.
1904    */
1905   public ResponseBeanMeta getResponseMeta() { return responseMeta.get(); }
1906
1907   /**
1908    * Returns the serializers to use for this method.
1909    *
1910    * @return The serializers to use for this method.
1911    */
1912   public SerializerSet getSerializers() { return serializers.get(); }
1913
1914   /**
1915    * Returns a list of supported accept types.
1916    *
1917    * @return An unmodifiable list.
1918    */
1919   public List<MediaType> getSupportedAcceptTypes() { return supportedAcceptTypes.get(); }
1920
1921   /**
1922    * Returns the list of supported content types.
1923    *
1924    * @return An unmodifiable list.
1925    */
1926   public List<MediaType> getSupportedContentTypes() { return supportedContentTypes.get(); }
1927
1928   @Override /* Overridden from Object */
1929   public int hashCode() {
1930      return method.hashCode();
1931   }
1932
1933   private static String toPartValue(Object value) {
1934      return value == null ? null : value.toString();
1935   }
1936
1937   private UrlPathMatch matchPattern(RestSession call) {
1938      for (var pp : pathMatchers.get()) {
1939         var pm = pp.match(call.getUrlPath());
1940         if (pm != null)
1941            return pm;
1942      }
1943      return null;
1944   }
1945
1946   /**
1947    * Whether this operation's path pattern matches the specified call.
1948    *
1949    * <p>
1950    * Unlike {@link #match(RestSession)}, this neither runs the matchers nor caches the path match on the session, so
1951    * it can be asked of any operation without disturbing the one about to run.
1952    *
1953    * @param session The call to check.
1954    * @return <jk>true</jk> if the path pattern matches.
1955    */
1956   boolean matchesPath(RestSession session) {
1957      return nn(matchPattern(session));
1958   }
1959
1960   /**
1961    * Identifies if this method can process the specified call.
1962    *
1963    * <p>
1964    * To process the call, the following must be true:
1965    * <ul>
1966    *    <li>Path pattern must match.
1967    *    <li>Matchers (if any) must match.
1968    * </ul>
1969    *
1970    * @param session The call to check.
1971    * @return
1972    *    One of the following values:
1973    *    <ul>
1974    *       <li><c>0</c> - Path doesn't match.
1975    *       <li><c>1</c> - Path matched but matchers did not.
1976    *       <li><c>2</c> - Matches.
1977    *    </ul>
1978    */
1979   protected int match(RestSession session) {
1980
1981      var pm = matchPattern(session);
1982
1983      if (pm == null)
1984         return 0;
1985
1986      var rm = requiredMatchers.get();
1987      var om = optionalMatchers.get();
1988      if (rm.length == 0 && om.length == 0) {
1989         session.urlPathMatch(pm);  // Cache so we don't have to recalculate.
1990         return 2;
1991      }
1992
1993      try {
1994         var req = session.getRequest();
1995
1996         // If the method implements matchers, test them.
1997         for (var m : rm)
1998            if (! m.matches(req))
1999               return 1;
2000         if (om.length > 0) {
2001            var matches = false;
2002            for (var m : om)
2003               matches |= m.matches(req);
2004            if (! matches)
2005               return 1;
2006      }
2007
2008         session.urlPathMatch(pm);  // Cache so we don't have to recalculate.
2009         return 2;
2010      } catch (Exception e) {
2011         throw new InternalServerError(e);
2012      }
2013   }
2014
2015   @Override /* Overridden from Context */
2016   protected FluentMap<String,Object> properties() {
2017      return super.properties()
2018         .a("defaultRequestFormData", getDefaultRequestFormData())
2019         .a("defaultRequestHeaders", getDefaultRequestHeaders())
2020         .a("defaultRequestQueryData", getDefaultRequestQueryData())
2021         .a("httpMethod", getHttpMethod());
2022   }
2023
2024   RestConverter[] getConverters() { return converters.get(); }
2025
2026   RestGuard[] getGuards() { return guards.get(); }
2027
2028   RestOpInvoker getMethodInvoker() { return methodInvoker.get(); }
2029
2030   RestOpInvoker[] getPostCallMethods() { return postCallMethods.get(); }
2031
2032   RestOpInvoker[] getPreCallMethods() { return preCallMethods.get(); }
2033   
2034   private static String joinnlFirstNonEmptyArray(String[]...s) {
2035      for (var ss : s)
2036         if (ss.length > 0)
2037            return joinnl(ss);
2038      return null;
2039   }
2040
2041   private static <T> Class<? extends T>[] classArray(Class<? extends T> value) {
2042      return (Class<? extends T>[])new Class<?>[] { value };
2043   }
2044
2045
2046}