Repository navigation
Conversation
… type construction Same Scala 3 blocker as the other connector files. sendRequest/extractEntity's TypeTag bound is vestigial - Connector.extractAdapterResponse, the only thing either method's T ever reaches, needs Manifest only - so it is dropped, keeping Manifest. convertId's isCustomerId/isAccountId checks dispatch on obp-commons model types (CustomerId, Customer, AccountId, CoreAccount, AccountBalance, AccountHeld) plus String, so they move into a new obp-commons object, RestConnectorTypes, computed once by the 2.13 compiler and consumed as plain values - the same pattern already used for SwaggerTypes/CustomJsonFormatsTypes/ConnectorEndpointsTypes. Verified with the full suite (./run_all_tests.sh path, run directly via mvn -pl obp-api -am test since -Dtest filtering isn't honoured here): 3749/3749 passed, 0 failed.
…lities Same Scala 3 blocker throughout: typeOf[T] for a generic type needs the Scala 2 compiler's TypeTag synthesis, which Scala 3 does not implement. code.bankconnectors.package (validateRequiredFields): the six dispatch types mix net.liftweb.common.Box/stdlib tuples with code.api.util.CallContext, an obp-api-only type - built at runtime via ReflectUtils.forType + appliedType, with WildcardType standing in for `_`. Confirmed against a throwaway test that the runtime-built and compiler-synthesized types agree under <:< in both directions - the only comparison this file's code actually performs; a stricter =:= check disagreed only because the compiler-synthesized tuple carries a pretty-printer hint the runtime-built one doesn't, which is cosmetic and doesn't affect subtyping. code.bankconnectors.generator.ConnectorBuilderUtil: same obp-api-only-type technique for Connector and Option[CallContext]; RabbitMQConnector_vOct2024 is likewise obp-api's own type, so ReflectUtils.forType replaces typeOf directly with no generic construction needed. code.util.Helper (convertId): dispatches on obp-commons model types (CustomerId, Customer, AccountId, CoreAccount, AccountBalance, AccountBalances, AccountHeld, TransactionId, TransactionCore, Transaction) plus String - moved into a new obp-commons object, HelperTypes, computed once by the 2.13 compiler, same pattern as SwaggerTypes. code.api.util.CodeGenerateUtils and JsonSchemaGenerator: every dispatch type in both files is JDK/obp-commons, so both get a matching obp-commons types object (CodeGenerateUtilsTypes, JsonSchemaGeneratorTypes). JsonSchemaGenerator also had one generic call site, generateSchemaForType[T: TypeTag] - with zero callers anywhere in the codebase, and permanently uncallable from Scala 3 code regardless of how its body is written (no caller can ever synthesize a TypeTag[T] under Scala 3), its signature changes to take the Type directly instead of inferring it from a type parameter. Verified with the full suite: 3770/3770 passed, 0 failures (Surefire audit).
The main-source TypeTag sweep missed two test files that reflect over obp-api's own types the same way ConnectorUtils/ConnectorEndpoints do - Connector, CallContext, OBPQueryParam, RestConnector_vMar2019 - so typeOf[T] for them needs the Scala 2 compiler's TypeTag synthesis, unavailable under Scala 3. Test sources compile under the same flip as main sources, so these need the same fix. ConnectorTest and RestConnector_vMar2019_FrozenTest move to ReflectUtils.forType (+ appliedType for the parameterized cases), same technique as the main-source connector files. Int/String, though stdlib, stay on the same runtime-construction path here rather than routing through an obp-commons constants object, to avoid a test file depending on a production module's file for two primitive types. Verified by running both tests directly: 8/8 passed.
…r removal None of these 41 files reference anything net.liftweb.mapper exports any more - the Doobie migration moved the real usage out from under them and the imports were never cleaned up. Left in place, they're dead weight now and become 105 noisy compile errors once the module switches off the Scala 2 compiler that tolerates an unused import silently. Found by removing every `import net.liftweb.mapper...` line across the 95 files that had one, recompiling, and restoring only the ones the compiler actually flagged (48 files needed Schemifier/DB/MetaMapper/etc. back - those are untouched). The remaining 41 compiled clean with the import gone, in both main and test sources. An import has no runtime effect, so a clean compile is the whole proof; the full suite (3770/3770, 0 failures) is the standing gate before commit, not evidence this particular change needed it.
The pom change (four parts, per the migration plan): obp-api gets its own
scala.version=3/scala.compiler=3.3.8 properties, which every inherited
${scala.version}/${scala.compiler} reference in the root pom's
dependencyManagement and plugin config now resolves against for this module
specifically - obp-commons, which does not override them, keeps resolving
the same references to 2.13. The three dependencies with no Scala 3 build
(lift-persistence, elastic4s-client-esjava, chill/chill-bijection) are
pinned to the new scala2.version property instead. scala-compiler/
scala-library - the jar DynamicUtil uses as an embedded runtime compiler for
dynamic-endpoint source strings, not the plugin that compiles this module's
own sources - stay pinned to scala2.compiler, since letting them follow the
module would start requiring Scala 3 syntax in every dynamic endpoint's
source. scala-collection-compat moves to 2.12.0, the first version with a
_3 build. -Ymacro-annotations and -Xsource:3 (the Scala 3 preview outpost
used while still compiling on 2.13) are removed from the compiler args in
favour of -source:3.3, along with the transitional -Wconf:msg=
Auto-application:e now that a real Scala 3 compiler enforces it directly.
With the compiler switched, obp-api's own source needed fixing in several
independent categories, none of which touch behaviour:
- ListResult[T] and Converter[T, D] (obp-commons) required a TypeTag at
their extends-clause call sites for D, several of which are obp-api types
(WebUiPropsCommons, MethodRoutingCommons, DynamicEntityCommons, ...) that
can no longer synthesise one under Scala 3. ListResult's itemType now
reflects the concrete list type off the runtime data instead (its only
caller, SwaggerJSONFactory, only ever sees non-empty curated doc
examples). Converter gains a sibling, ConverterWithType, for obp-api's
eight subclasses - same for OBPEnumeration/OBPEnumerationWithType and
obp-api's one subclass (AuthenticationType) - taking the Type as a
constructor parameter built via ReflectUtils.forType instead of a context
bound, the same pattern the earlier TypeTag-removal pass already
established for SwaggerJSONFactory and the connector files.
- Half a dozen call sites relied on an implicit Manifest[T]/TypeTag[T] never
actually used by the method body (unboxFull and its four callers in
APIUtil, validate/validateMultiple in code.bankconnectors) - dropped
rather than fixed, since nothing downstream needed them. One genuine use
(Caching.memoizeSyncWithImMemory[List[T]] in
MappedDynamicResourceDocProvider) needed Manifest[List[T]] composed
explicitly via Manifest.classType, since Scala 3 does not derive it from
an in-scope Manifest[T] the way Scala 2 did.
- A recurring pattern across ~15 call sites: a connector trait method
(List[Bank], List[DynamicEntityT], List[MethodRoutingT], ...) assigned
into a field or variable typed to the concrete *Commons case class.
Scala 2 accepted this un-narrowed; Scala 3 does not, and in every case
the connector in question (LocalMappedConnector, the Doobie-backed
providers) only ever constructs the concrete case class, so an explicit
.asInstanceOf[List[XCommons]] (or the object's own .toCommons/
.toCommonsBox for the non-List cases) states what was already true.
- Nine files had indentation Scala 3's significant-whitespace parser
rejects: match arms at a shallower indent than their siblings
(Glossary.scala, AuthUser.scala), a `val` block whose continuation
statements sat deeper than the val they followed so the compiler treated
them as part of its initializer instead of new statements
(JSONFactory1_4_0.scala, JSONFactory3.0.0.scala), and tab/space mixing
(ModeratedBankingData.scala).
- Half a dozen small, unrelated syntax/API-surface breaks: pekko-http's
HttpProtocol("HTTP/1.1") construction (its constructor and apply are both
package-private; the correct accessor is the HttpProtocols object's
pre-built constant), the removed do-while loop syntax (Helper.scala),
scalameta 4.13.6 moving Tree#collect from a plain method to a standalone
scala.meta.contrib.TreeOps function (ApiRole/ErrorMessages's two
self-validation lint helpers, one of them asserted by a real test),
org.scalameta.logger.elem's sourcecode.Text macro no longer available
(three debug-print call sites, replaced with plain string interpolation),
a genuinely unrelated-type == comparison (Box[String] == String) that
Scala 2 silently always evaluated false on and Scala 3 now rejects at
compile time (Http4s140.scala; fixed with .exists(_ == ...) rather than
preserved), and a wildcard-imported helper's same-named extension shading
the stdlib String#splitAt(Int) Scala 2 preferred and Scala 3 does not
(APIUtil.scala; rewritten as two substring calls).
- Scala 3 requires an override's laziness to exactly match what it
overrides, in both directions - Scala 2 allowed a lazy val to implement
an abstract strict val. OBPRestHelper.version/versionStatus and
Saveable.value are now declared lazy (most of their ~30 implementers
already were, via ScannedApis or their own `lazy val`); the three
remaining strict-val implementers (MappedSaveable, SaveableAtm,
SaveableCrmEvent, all in LocalMappedConnectorDataImport.scala) get their
constructor parameter renamed and a `lazy val value = ...` added, since a
case-class constructor parameter cannot itself be declared lazy.
- Six `case _: APIFailureNewStyle` branches (ErrorResponseConverter,
ResourceDocMiddleware) were unreachable: APIFailureNewStyle is a plain
case class, not a Throwable, so nothing thrown into a .attempt/exception
handler is ever actually an instance of it - callers throw
new Exception(<its JSON encoding>), which the adjacent fallback branch
already parses back out via tryExtractApiFailureFromExceptionMessage /
the same pattern. Scala 2's reachability check was a warning; Scala 3's
is an error. Removed rather than kept, since the real path already
existed alongside them.
Verified by `mvn -pl obp-api -am compile`: clean, zero errors. test-compile
and the full suite are the next steps - not yet run under this compiler.
- ScalaTest's Feature(...)/Scenario(...) DSL calls return a (=> Unit) => Unit
function that must be applied to its trailing block in the same
expression. Written across the same two lines
(`Feature("...")` then `{` on the next line), Scala 2 accepted the split;
Scala 3 treats the first line as a complete, unapplied statement.
Mechanical fix across every occurrence: merge the block onto the call's
line.
- org.scalameta.logger.elem(x)'s sourcecode.Text[Any] macro is gone from
scalameta 4.13.6 (_3) the same way it is in the main-source callers fixed
earlier - replaced with plain string interpolation, same as those.
- AtmsTest/BranchesTest (x2) mock connectors matched the wrong parameter:
getAtmFromProvider/getBranchFromProvider pattern-matched on the second
parameter (AtmId/branchId) against BankId-typed fixtures
(bankWithLicense/BankWithLicense), copy-pasted from the sibling
getAtmsFromProvider/getBranchesFromProvider method one scope up, which
correctly matches on the first (bank/bankId) parameter. A cross-type
pattern can never match, so these mocks always fell through to None -
Scala 2's pattern-type checking accepted the mismatch silently; Scala 3
rejects it at compile time. Fixed to match on the bank parameter, as the
sibling method and the "have it return branches even for the bank
without a license" comment both intend.
- RegulatedEntityTest's `'success` is a removed symbol literal -> Symbol
("success").
- CacheKeyCallContextTest's Array.empty needed the same explicit type
argument as the two main-source occurrences fixed earlier
(Array.empty[File]) for the same inference reason.
- OBPRestHelperTest's local OBPRestHelper subclass needed lazy val version/
versionStatus, matching OBPRestHelper's now-lazy abstract declarations.
Verified by `mvn -pl obp-api -am test-compile`: clean, zero errors. Full
suite is next.
Every _3 dependency pulls in its own scala3-library_3 transitively, each at
whatever version it happened to build against (observed range 3.0.0-3.3.6
across the dependency tree), and Maven's mediation was resolving that down
to 3.3.4 - older than the 3.3.8 compiler actually compiling this module's
sources.
The mismatch is not cosmetic: the first full-suite run under the flipped
compiler hung every shard indefinitely at startup with no output past
classloading, silently, well before any test could log anything. The only
clue was a JVM warning naming scala.runtime.LazyVals - the class Scala 3
uses to implement `lazy val` initialization - loaded from
scala3-library_3-3.3.4.jar. That machinery changed its locking
implementation more than once across the 3.3.x line; running bytecode
compiled for 3.3.8 against 3.3.4's runtime support class is exactly the
kind of mismatch that would deadlock lazy val initialization rather than
fail cleanly. This migration's own changes made that failure mode likely:
OBPRestHelper.version/versionStatus and Saveable.value both went from
strict to lazy val in the previous commit, and both sit on the CallContext/
Connector initialization path every request and every test touches.
A direct dependency in obp-api's own pom overrides the transitive version
regardless of tree depth, pinned to ${scala.compiler} so the two can never
drift apart again. Verified: `mvn -pl obp-api dependency:tree` now resolves
a single scala3-library_3:3.3.8 with no other version anywhere in the tree,
and `mvn -pl obp-api -am test-compile` stays clean.
sensitivePatterns' initializer calls APIUtil.getPropsAsBoolValue, the first touch of APIUtil$ on that thread, which triggers APIUtil$'s own class init - eagerly evaluating publicAppUrlDefaults, which logs a debug message, which (every log call in MdcLoggable routes through maskSensitive) calls back into maskSensitive -> sensitivePatterns, on the same thread, before the first call returns. Scala 2's lazy val used a reentrant `synchronized` block, so this recursive call silently passed through; Scala 3's LazyVals uses a CountDownLatch, which is not reentrant, so the thread deadlocks waiting on a latch only it could count down - every test shard hung identically at startup. A ThreadLocal flag detects that one-time computation window and returns the message unmasked rather than recursing; everything logged in that window is APIUtil/SecureLogging's own prop-driven startup, not request data.
…sLazy miss getFieldValues filters candidate members by isLazy/isVal/isVar, which read from Scala's own declaration metadata (ScalaSig for Scala 2, TASTy for Scala 3). scala.reflect.runtime.universe - the Scala 2.13 reflection library obp-commons is pinned to - has no TASTy reader, so all three come back false for every member of a Scala-3-compiled class; only the bytecode-level shape (a zero-arg method with a return type) survives. ExampleValue.exampleNameToValue (a Scala-3-compiled obp-api object, scanned via this function) resolved to an empty map as a result, and any downstream lookup against it threw at initialization time. The added clause recovers that shape, but it also matches a case class's own synthetic zero-arg methods (toString, hashCode, productArity, ...), so it is only safe on a target whose zero-arg methods are all real fields - true for the plain objects getFieldsNameToValue scans, not for an arbitrary case-class instance. JSONFactory1_4_0's generic field-extraction branch reads a case class instance's fields for JSON schema output, so it is switched to scala.Product's productElementNames/productIterator instead, which needs no reflection metadata at all and can't pick up synthetic methods by construction.
…companion values ran eagerly, in OBPEnumerationBase's own constructor - while the concrete companion object (e.g. AuthenticationType$) is still mid-<clinit>, before the JVM marks the class initialized. Scala's runtime reflection, asked to inspect that same not-yet-initialized class from inside its own construction, silently returned every member symbol with isModule false, so decls.filter(_.isModule) found nothing and the assertion threw at <clinit> time - reproduced identically for a Scala-2-compiled companion once isolated, so this is a self-reflection-during-own-<clinit> problem, not a Scala-3/TASTy one. Deferring to first external access (lazy val), after the class is fully initialized, gets decls.filter(_.isModule) back to finding the right symbols. Symbol -> runtime instance still can't go through mirror.reflectModule(sym).instance though: for a Scala-3-compiled nested module, ModuleMirror's own name resolution reconstructs the wrong binary name and reflectModule throws ClassNotFoundException. That step is done by hand instead - a nested object's binary name is always "<outer's binary name><simple name>$" regardless of which Scala version compiled it, and loading it plus reading its MODULE$ field is reliable either way. Order is a narrower, separate caveat: decls preserves source declaration order for a Scala-2-compiled companion (asserted on by OBPEnumerationTest), but not for a Scala-3-compiled one, where it comes back in some other deterministic order instead. AuthenticationType, the only Scala-3-compiled subclass today, uses values only as an unordered set, so this doesn't bite in practice; documented inline for whoever adds the next one.
…Sig poisoning Four layered problems, found and fixed in sequence, all on the path to letting json4s actually extract/decompose a Scala-3-compiled case class: 1. org.json4s:json4s-native_3:4.1.0-M8 (Maven Central's last publish there, 2024-11-07) still throws "Can't find ScalaSig for class ..." extracting a Scala-3-compiled case class. The project moved to io.github.json4s after M8; 4.1.1 there is the first stable release with a working Scala-3 quotes-based reflector (core/src/main/scala-3/.../ScalaSigReader.scala upstream). Root pom, obp-commons and obp-api all repoint to the new groupId. 2. obp-commons (permanently Scala 2.13) and obp-api (now Scala 3) end up needing both json4s-native_2.13 and json4s-native_3 transitively, and both publish org.json4s.reflect.ScalaSigReader under the identical class name with a different implementation - the _2.13 one has no notion of the Scala-3 quotes-based reader. Whichever jar the classloader resolves first wins for every caller, and it consistently picked _2.13, silently reintroducing the ScalaSig error for Scala-3-compiled classes even with 4.1.1 on the classpath. obp-api excludes json4s-native_2.13 transitively from obp-commons, forcing the whole reactor onto _3 - the "verify binary compatibility" step the json4s-scala3-matrix memory flagged as the fallback if json4s's own upgrade wasn't enough on its own (it wasn't). 3. That exclusion breaks obp-commons's own json4s code in turn: JsonSerializers.scala's CustomFormats (extends DefaultFormats) and its Serializer[T] implementations are Scala-2.13-compiled trait mixins: Scala 2 compiles a trait's field initialization through a $init$ forwarder method that Scala 3 does not generate, so a $init$ call against the _3 jar's Formats/Serializer throws NoSuchMethodError at runtime. JsonSerializers.scala and JsonBoxSerializer.scala move into obp-api (code.api.util) so they get compiled by Scala 3 against the Scala-3 json4s jar they now depend on; JsonAble - a plain interface with no trait-field-init concerns, mixed into several obp-commons case classes that must stay in obp-commons - splits out to its own file and stays behind, and the two Scala-3-only TypeTag call sites the move exposed (ru.typeOf[optional], ru.typeOf[Mapper[_]], plus a handful of ru.typeOf[Long/Double/...]) go through ReflectUtils.forType instead. 4. Even with the right reflector selected, a ScalaSig-pickled override whose signature names org.json4s.JsonAST.JValue directly is unreadable from a Scala-2.13-compiled class once json4s-native_2.13 is off the classpath - reflecting anywhere near it throws "unsafe symbol JValue (child of class JsonAST) in runtime reflection universe". Every obp-commons toJValue override (ApiVersion, CommonModel's CounterpartyLimit, Enumerations' SimpleEnum, RequiredFieldValidation's three implementors) is repointed at the json.Formats/json.JValue aliases in JsonAliases.scala instead of importing org.json4s directly - those aliases are themselves Scala-2.13-compiled symbols in the same package, so they stay resolvable, and the method bodies are unaffected since json.JValue =:= org.json4s.JValue. Left over after all four: json4s's Scala-3 ScalaSigReader.readField (used to recover a generic field's erased type argument, e.g. an Option[String]) throws NoSuchElementException: None.get introspecting a Scala-2.13-compiled DTO - a genuine upstream limitation, unchanged between json4s 4.1.1 and 4.2.0-M4. RabbitMQConnector_vOct2024's two ResourceDoc examples that hit it (Extraction.decompose on InBoundOpenCorridorCreditNotificationData / InBoundOpenCorridorSettlementData, both obp-commons DTOs with Option fields) are hand-built with the JsonDSL ~ operator instead, since they are fixed example literals, not runtime data. ConnectorUtils.scala and MSsqlStoredProcedureBuilder.scala have generic Extraction.decompose(Any) call sites that can hit the same bug on arbitrary connector messages and still need a real fix, not a one-off literal rewrite.
Its own docstring promised "call by name methods OR val values", but the code only ever handled the method branch: it asserted methodSymbol.isMethod unconditionally, which was true for every Lift Mapper entity this was written against (Mapper exposes every column as a call-by-name accessor def). Post-Mapper-to-Doobie migration, an entity like MappedBankAccount is a plain case class, so its fields (e.g. accountPrimaryKey) are ordinary constructor vals - isMethod is correctly false for them, and the assertion threw "accountPrimaryKey is not method in Object MappedBankAccount(...)" for every one, breaking findBankIdIn and cascading into a 500 on every connector call that routes through it (surfaced here via saveHistoricalTransactionViaEndpoint, but not specific to it). Not a Scala-3-reflection gap like the isVal/isVar/isLazy ones elsewhere in this file: confirmed via an isolated diagnostic that isVal/isMethod are both read correctly here, they just don't match what this function assumed. Added the missing val/var branch, reading the field directly instead of searching for a zero-arg method alternative.
…" field Copying a same-named parameter from a source object to a target constructor worked by reflecting it as a method; when the source symbol wasn't a method it fell back to reflecting a completely unrelated hardcoded field named "attributes" instead of the actual parameter. That fallback firing at all depended on the source field genuinely not being a call-by-name method - true for whatever original case needed it, but also true for any ordinary case class constructor val, which is what most source objects going through ConverterWithType.toCommons actually are. Every plain val parameter hit the "attributes" fallback, and once no source object actually had an "attributes" member either, that threw ScalaReflectionException: <none> is not a method - surfaced here via createDynamicEntityImpl's use of ConverterWithType, 500ing customer/bank dynamic entity creation across almost every DynamicEntityTest scenario. Same shape as the getCallByNameValues fix: added the missing val/var branch, reading the field directly instead of assuming every source member is a method. The "attributes" fallback is kept as the last resort, unchanged, for whatever case actually relies on it.
…f converting it NewStyle.function.getDynamicEntities returns List[DynamicEntityT] - the provider trait - not List[DynamicEntityCommons]. Seven call sites across Http4s400/Http4s600 (system/bank/my dynamic entity listing endpoints) took that as List[DynamicEntityCommons] via a blind asInstanceOf, relying on the runtime instances happening to already be DynamicEntityCommons. They threw ClassCastException as soon as that stopped being true, 500ing every affected DynamicEntityTest scenario. DynamicEntityCommons's own companion is a ConverterWithType[DynamicEntityT, DynamicEntityCommons] - it exists specifically to do this conversion via reflection (the same ReflectUtils.toOther machinery fixed for Scala 3 case-class-val sources earlier this session), so the cast is replaced with DynamicEntityCommons.toCommonsList(...) instead of asInstanceOf.
…tching, getEnumContainer Three more reflection gaps the full suite surfaced beyond the 5 originally-crashing classes (all previously masked by the boot crash never letting these code paths run): 1. SwaggerTypes.scala used typeOf[JObject] et al. directly - needs TypeTag synthesis for org.json4s's own type symbol, which scala.reflect.runtime.universe can't resolve once json4s-native_2.13 is off obp-api's classpath (same ScalaSig-poisoning shape as the earlier json.* alias fixes, but via typeOf instead of a plain import). Rewritten to build every json4s-involving Type from ReflectUtils.forType + ru.appliedType instead of typeOf, which needs no TypeTag synthesis. Also fixed the class names themselves: org.json4s.JsonAST.JObject doesn't exist as a loadable class in json4s 4.x - JsonAST is a legacy compatibility object, the classes live directly under org.json4s. 2. getFieldValues' widened zero-arg-method filter (from the isVal/isVar/isLazy fix earlier this session) matched too much: java.lang.Object's notify()/wait() (reflectMethod on those outside a synchronized block throws IllegalMonitorStateException), scala.Any's asInstanceOf/ isInstanceOf (reflectMethod refuses to invoke a generic method at all), and even an unrelated JDK-internal interface method on whatever object JSONFactory1_4_0's unfiltered fallback branch happened to be looking at. Restricted the clause to it.owner == tp.typeSymbol - a member actually declared on the target's own class, never one it merely inherits - which excludes all of the above at once instead of naming bad owners one at a time. 3. OBPEnumeration.getEnumContainer (both overloads) used knownDirectSubclasses.head to find any one enum value and walk back up to its companion. knownDirectSubclasses reads Scala's own declaration metadata the same way isVal/isVar/isLazy and OBPEnumerationBase.modules do, and a Scala-3-compiled sealed trait reports zero known subclasses to it - .head then threw NoSuchElementException. The function never needed a subclass in the first place, only the companion - and a companion's binary name is always "<trait's name>$" regardless of compiler, the same technique OBPEnumerationBase.modules already uses. getValuesByInstance's own getInterfaces().headOption lookup (used to find which trait an enum value implements before calling getEnumContainer) got a matching fix: Scala 3 doesn't always list an EnumValue-derived trait before EnumValue itself, so headOption sometimes returned EnumValue - now finds the interface that extends EnumValue without being it. Combined verification (the 5 originally-crashing classes + SwaggerFactoryUnitTest + ResourceDocsTechnologyTest): 375/377, no regressions from any of these three changes. ResourceDocsTechnologyTest's remaining 2 failures are a separate, still-open issue - see project_scala3_json4s_extraction_saga memory.
…tEnumContainer cast bug Two more root causes on the same "resource docs generation" path, found chasing the same 2 scenarios through successive fixes: 1. JSONFactory1_4_0's unfiltered getFieldValues fallback branch reflected over whatever non-Product AnyRef it was given, with no check that the value was ever meant to be schema-relevant OBP data. Somewhere in the v5.0.0/v6.0.0 resource doc tree this reached a genuine java.util.stream.ReferencePipeline object, and getFieldValues' isMethod-shaped filter (declared directly on the target's own class, so not excluded by the owner check from the previous commit) picked up its internal opIsStateful() method, which reflectMethod can't invoke without an InaccessibleObjectException. Restricted the branch to ReflectUtils.isObpObject(entity) - a JDK type was never meant to reach this code path at all. 2. Underneath that: OBPEnumeration.getEnumContainer's return type was hardcoded to OBPEnumeration[T]. AuthenticationType (obp-api, Scala 3) extends OBPEnumerationWithType[T], a sibling of OBPEnumeration[T] under the shared OBPEnumerationBase[T] - not a subtype of it - so the function's own .asInstanceOf[OBPEnumeration[T]] threw ClassCastException the moment it was ever asked to resolve AuthenticationType specifically (a live bug independent of this session's knownDirectSubclasses fix, exposed by it rather than caused by it, since OBPEnumerationWithType didn't exist until AuthenticationType was introduced). Every caller only uses values/withNameOption/withIndexOption/example, all declared on the shared OBPEnumerationBase, so widening the return type to it is a pure fix with no narrowing loss. SwaggerFactoryUnitTest + ResourceDocsTechnologyTest: 13/13, both fully green.
… frozen test RestConnector_vMar2019_FrozenTest aborted its whole shard with Symbols$CyclicReference: illegal cyclic reference involving class BodyPartParser. Bisection showed this is not one bad member among many: any attempt to resolve RestConnector_vMar2019's own scala-reflect Type - decls, baseClasses, or asking any of its members whether they override something - forces scala.reflect.runtime to complete an unrelated symbol reachable from its inheritance chain, and that completion fails inside the JVM-wide shared symbol table, not inside the specific symbol being asked about. Per-symbol try/catch around the caller's own loop cannot catch it, no matter how granular. Route around it instead of trying to catch it: get the override-eligible method names from Connector's type, which is a plain OBP domain trait and resolves cleanly, then cross-reference against RestConnector_vMar2019's own declared methods via java.lang.Class reflection, which never touches scala.reflect.runtime.universe and so cannot hit this. Verified byte-for-byte equivalent to the old list against the persisted frozen metadata file.
SwaggerScalarFieldTypeTest and SwaggerOptionFieldTypeTest declared their fixture case classes nested inside the AnyFlatSpec test class. SwaggerJSONFactory. translateEntity reflects on a fixture value's runtime type via scala.reflect.runtime.universe, and for a nested case class that also means resolving the enclosing class - here a ScalaTest suite mixing in Assertions. Walking that unrelated third-party hierarchy throws (AssertionError: no symbol could be loaded from class org.scalatest.Assertions$UseDefaultAssertions$, and separately illegal cyclic inheritance once the enclosing class's own type becomes unresolvable). Moving the fixtures to file scope removes the enclosing class scala-reflect would otherwise have to walk. No production code changed.
…la 3 ToolBox is Scala 2.13-only and cannot read TASTy, so it fails on any dynamically-compiled snippet that references obp-api's own Scala-3-compiled classes (OBPReturnType, HttpCode, and friends injected via DynamicUtil.importStatements). This was the largest remaining source of test failures after the Scala 3 flip. DotcScalaCompiler drives dotty.tools.dotc.Driver directly: each distinct source is wrapped as a synthetic top-level object compiled to a temp directory against the running JVM's own classpath, then loaded with a URLClassLoader parented on the current thread's context classloader. Two things the wrapping has to get right, both found by running the actual test suite rather than assumed up front: - top-level type definitions (case class/class/object/trait/enum) are hoisted out as direct siblings of the result method rather than nested inside its body, because json4s's Reflector refuses to extract into a case class "defined in function bodies" - exactly what a naive whole-snippet block wrap would produce for DynamicUtil.toCaseObject's generated case classes. - the result accessor is a def, not a val: a runtime-compiled dynamic endpoint body can contain a `return` inside a nested lambda (recovered later as a NonLocalReturnControl by Sandbox.runInSandboxIO), and that only compiles when there is a real enclosing method to target. A val compiles to a bare field initializer with no such method. Compiled classes are kept on disk for the JVM's lifetime (registered for delete-on-exit rather than deleted immediately after evaluation): a class referenced only inside a returned closure's body is linked lazily, on first invocation of that closure, which can happen long after compilation returns - deleting the output directory right after evaluate() intermittently broke exactly that case. Verified: DynamicUtilTest, DynamicCompilerKillSwitchTest, DynamicCompilerFourChainPocTest, ConnectorMethodTest, EndpointMappingTest, EndpointMappingBankLevelTest, DynamicMessageDocTest, DynamicResourceDocTest, DynamicCodeKillSwitchTest, MethodRoutingTest, ConnectorProxyObjectMethodsTest. Four remaining failures (EndpointMappingTest, EndpointMappingBankLevelTest, MethodRoutingTest, ConnectorProxyObjectMethodsTest) are unrelated pre-existing issues - confirmed by ClassCastExceptions and reflection mismatches that occur entirely within the same classloader, with no DynamicScalaCompiler involvement in their stack traces.
…able by name InternalConnector.methodNameToSymbols filters Connector's decls with !t.isVal && !t.isVar to decide which members dynamic code may implement. Connector is now Scala 3-compiled and read via Scala 2.13's scala.reflect.runtime.universe, under which isVal/isVar report false for it - a val getter and a zero-arg def compile to the identical JVM shape, so the distinction is source-level information a non-TASTy reader cannot recover from any flag. messageDocs leaked through as if it were a genuine connector method, throwing IllegalStateException instead of falling through to the stub path. Connector's trait body declares exactly two public vals directly (formats, messageDocs; everything else at that scope is protected and already excluded by the isPublic check, which reflects a JVM access modifier and reads correctly across the compiler boundary). Excluded both by name.
Four response-serialization sites in Http4s310/Http4s400 blindly cast a provider-returned List[XT] (the trait) to List[XCommons], on the assumption that the provider only ever constructs XCommons. That assumption no longer holds where a Doobie-migrated provider (MappedMethodRoutingProvider, DoobieCardAttributeProvider) returns its own row type implementing the same trait: management/method_routings, management/endpoint-mappings, management/banks/BANK_ID/cards/CARD_ID, and management/webui_props all threw ClassCastException instead of serving a 200/201. Each affected XCommons companion already extends Converter/ConverterWithType for exactly this purpose - the singular per-item getters in the same files already used its implicit toCommons conversion correctly. Switched the four list sites to the same companion's toCommonsList instead of casting.
… gap json4s's default Reflector-based decompose calls ScalaSigReader.readField (a Scala 3 compiler staging run) whenever a field's generic type argument is erased to java.lang.Object on the classfile - the case for an Option[T] field where T is a primitive value type. readField only knows how to recover that argument from TASTy, so it throws NoSuchElementException: None.get for any Scala-2.13-compiled class, since none of them carry TASTy. This hits any obp-commons DTO with such a field, directly or nested arbitrarily deep inside another obp-commons value being decomposed (e.g. every OutBound message embeds OutboundAdapterCallContext -> User, and User.isDeleted: Option[Boolean] is exactly this shape), and was crashing code.api.v3_0_0.ViewsTests (via the UpdateViewJSON body built on the test side) and code.api.v2_2_0.API2_2_0Test's Get Message Docs scenarios (via connector example messages) with a server-side 500. Add ObpCommonsProductSerializer, registered last in JsonSerializers.serializers so every more specific existing serializer still gets first refusal. It builds the JSON for any com.openbankproject.commons case class from ReflectUtils.getConstructorArgs instead of the default Reflector - ReflectUtils reads Scala-2.13-compiled classes through their own compiler's runtime reflection, which has no TASTy dependency. Because it is registered in the shared Formats chain rather than invoked at one call site, nested obp-commons values get the same treatment automatically at any depth. Deliberately scoped to the com.openbankproject.commons package rather than also matching obp-api's own classes, which are Scala 3-compiled and reflecting those via scala.reflect.runtime.universe has its own, unrelated set of gaps.
… method enumeration Connector.connectorMethods/implementedMethods enumerate Connector's own decls to decide which members are genuine dynamic-dispatch connector methods. Two kinds of Scala 3-compiled trait member leaked through and got miscounted: - synthetic cross-module setters for Connector's own protected vals (bankTTL, formats, ...), named "_setter_$xyz_=" or "_setter_@xyz_=" - isVal/isVar report false for them under Scala 2.13's scala.reflect.runtime.universe, the same gap fixed for InternalConnector.messageDocs, but connectorMethods needed the same exclusion independently since implementedMethods unions it in; - the eight protected implicit def adapter conversions (boxToTuple, tupleToBoxTuple, OBPReturnTypeToBox, ...) - both isPublic and isImplicit are equally unreadable cross-compiler for these, so both were tried and both failed; named explicitly instead. ConnectorTest's own WrongOutBoundType.unapply needed a third, narrower fix: Option[AnyVal] connector method parameters (dependents: Option[Int], isActive: Option[Boolean]) read back as Option[Object] - the JVM parameter signature boxes/erases the value type with no TASTy to recover it from. A wildcard-tolerant type comparison is now used only for the final by-name field check, not for the CallContext/query-params shape detection earlier in the same method - using it there deleted the erased-looking fields from the comparison entirely instead of tolerating their type.
Every diff FrozenClassTest reported was one of three benign, already- understood renderings from the migration, not a real API structure change: json4s's package rename (org.json4s.JsonAST.JValue -> org.json4s.JValue, already normalised in RestConnector_vMar2019_FrozenTest), an Option[AnyVal] connector/JSON field reading back as Option[Object] under Scala 2.13's scala.reflect.runtime.universe (a JVM erasure gap with no TASTy to recover the original argument from - same shape already fixed in Connector.scala and ConnectorTest.scala), and BigDecimal now rendering as its fully-qualified scala.math.BigDecimal. Regenerated via FrozenClassUtil.getFrozenApiInfo, per the test's own stated remediation.
…readField gap json4s's Scala 3 ScalaSigReader.readField throws NoSuchElementException extracting an Option[AnyVal] field (e.g. User.isDeleted: Option[Boolean]) declared on a Scala-2.13-compiled obp-commons type, because it can only recover the erased type argument by reading TASTy and those classes have none. This is the extract-direction mirror of the earlier ObpCommonsProductSerializer decompose fix. Add ObpCommonsProductDeserializer, which builds any concrete obp-commons case class directly from its constructor parameter names/types (read via scala.reflect.runtime.universe, which resolves the real type argument correctly) instead of letting json4s's default Reflector walk the class. Along the way, fix two pre-existing bugs this newly-exercised code path uncovered: ReflectUtils.invokeConstructor threw for any class with an auxiliary constructor (e.g. BankCommons), and a missing @optional field with no Option wrapper had no tolerated default.
…optional The deserializer's fallback for a missing (JNothing) constructor field defaulted every primitive to its zero value and every non-primitive to null, modeled on JNothingSerializer - a mechanism for a different problem, schema evolution in a stored/cached JSON blob predating a new column. Applied inside generic extraction, the same tolerance also covered genuinely untrusted input: a POST body missing a required field extracted successfully instead of failing, either producing a wrong result (CreateViewJson missing every boolean field returned 201 instead of 400) or deferring the failure downstream past where it could be caught as a proper 400 (a payment body missing its amount built a null-carrying instance that later NPE'd as an uncaught 500). Removed the primitive defaults entirely - a missing primitive now falls through to Extraction.extract, which throws MappingException for it, matching json4s's own behavior for a required field. Replaced the blanket non-primitive null-default with a check on the constructor parameter's own annotations: only default to null when the field is explicitly marked @optional (com.openbankproject.commons.util.optional, already used for exactly this on fields like BankCommons.swiftBic), checked before extraction in buildInstance rather than inferred from the missing field's shape alone.
frozen_type_meta_data.txt is the reviewable text sibling of the binary frozen_type_meta_data blob, and FrozenMetaDataTextTest fails when the two disagree. The blob was regenerated for the Scala 3 flip; its text rendering was not, until now. Rewritten via FrozenMetaDataText's own generator - the diff is the same three benign renderings already covered by the blob regeneration (json4s's package rename, Option[AnyVal] reading back as Option[Object], and one now-added type: JArrayBody removed, matching the blob).
getPrimaryConstructor took .alternatives.head - the first overloaded constructor scala-reflect happened to enumerate. For a class with only one constructor this is harmless; for one with an auxiliary constructor as well (code.methodrouting.MethodRoutingParam(key: String, value: String) also declares def this(jObject: JObject), a JSON convenience constructor), the enumeration order is not guaranteed and differed between environments - locally it consistently returned the real primary constructor, in CI it consistently returned the auxiliary one instead, corrupting every reflection built on top of it for that type (constructor param info, instance construction, JSON extraction). Select by isPrimaryConstructor, a real flag scala-reflect exposes for exactly this, instead of position.
…a symbol flag The previous fix (13418d5) replaced positional .alternatives.head with a filter on isPrimaryConstructor, a flag scala-reflect exposes specifically for this. It read correctly for every local check but did not change CI's answer at all - CI kept picking MethodRoutingParam's auxiliary `def this(jObject: JObject)` as if it were the primary constructor, identically to before that fix landed. Replaced the flag-based selection with a JVM-bytecode-only one: a case class's primary constructor parameters are exactly its declared instance fields. Pick the constructor alternative whose every parameter name appears in the class's own declared fields (ordinary classfile metadata, unaffected by TASTy or by whatever made isPrimaryConstructor disagree between environments), falling back to positional selection only if none match. Kept code.util.PrimaryConstructorDiag2Test in this commit rather than deleting it after local verification, since local verification of this exact bug has now been wrong twice - it prints MethodRoutingParam's declared fields, constructor alternatives, and isPrimaryConstructor flag directly, so CI's own log carries the ground truth this time if this fix also fails there.
… the fix Kept deliberately in the previous commit so CI's own log would carry ground truth about isPrimaryConstructor/declared fields for MethodRoutingParam if the field-name-based fix also failed there. It didn't - all 9 CI test shards and compile now pass. The diagnostic has served its purpose.
NOW() does not exist on SQL Server or Oracle. CURRENT_TIMESTAMP is the standard spelling and every supported database has it.
The account directory queries joined strings with || and string_agg. On MySQL || is a logical OR and string_agg does not exist, and Oracle calls it LISTAGG. DoobieUtil.concat and stringAgg now write CONCAT and GROUP_CONCAT on MySQL, LISTAGG on Oracle and the existing forms elsewhere, with SQL Server keeping its CONCAT cast to NVARCHAR(MAX).
On Oracle the tables live in the user's schema and the url names only the server's service, so the disposable database guard now checks that user's name.
The setup-test-database action starts MySQL 8.4 and MariaDB 11.4 with lower_case_table_names=1, which the queries need, and Oracle Free 23 with a schema user the disposable database guard accepts. The workflows write that user and password into the test props.
Their preconditions read information_schema.columns, which Oracle does not have; a column.catalog property now reads user_tab_columns there. Oracle also cannot alter a VARCHAR2 into a CLOB, so the six dynamicresourcedoc text columns that are later widened to the text type start as CLOB on Oracle, and the widenings mark themselves run. On the other databases both properties expand to the text they replace, so no checksum moves.
The widening changesets now read the column catalogue through ${column.catalog}, which is
information_schema.columns except on Oracle.
The live metric table reads a NULL as its metric id, cast to BIGINT so both metric tables share one row type. MySQL casts to SIGNED and Oracle has no BIGINT, so the listing failed there with a syntax error.
A query written with sql"..." ends without a space after its last parameter, so the LIMIT that firstRowOf appended made $1LIMIT, which PostgreSQL 16 refuses.
Seven inserts wrote true or false in their VALUES, and the four maker-checker approvals used a bound boolean directly as a CASE condition. SQL Server refuses both, reading the literal as a column name. The values are now bound, and the CASE compares the flag with true.
…erver and Oracle information_schema.indexes is an H2 extension, so the index checks failed on every other database the suite now runs on. H2 and Postgres keep their catalogue queries; the others read DatabaseMetaData.getIndexInfo.
MySQL parses a column-level REFERENCES and ignores it, so the blocking row did not block anything and the cascade the test expects to fail succeeded. A table-level FOREIGN KEY is enforced everywhere; Oracle gets NUMBER(19) for the BIGINT it lacks.
…er test The old organisation tables were created with GENERATED BY DEFAULT AS IDENTITY and IF NOT EXISTS, which SQL Server and MySQL do not take. Existence now comes from the JDBC metadata, and the key, boolean and timestamp types follow the database.
A test read a row with LIMIT, another created its probe table with IF NOT EXISTS, and two looked columns and tables up in information_schema. SQL Server refuses the first two and Oracle has no information_schema. They now use DoobieUtil.firstRowOf and the JDBC metadata, and the dialect test expects OFFSET ... FETCH on Oracle as on SQL Server.
SQL Server's VARCHAR holds only the code page of the database, so text outside it came back as question marks. A Liquibase data type registered for SQL Server alone renders VARCHAR(n) as NVARCHAR(n), as the Mapper driver did. The changelog is unchanged, so no checksum moves. The service registration needs its own .gitignore exception.
Liquibase recognises MariaDB as mariadb even through the MySQL driver, so the properties and changesets written for mysql did not reach it, and its tables were created with the property names left in. Every dbms that names mysql now names mariadb with it.
Their default collations ignore case and trailing spaces, so the upper-case migration found nothing to change. BINARY makes both count, as the binary collation already does on SQL Server.
Six test inserts wrote true or false and one wrote NOW(), which SQL Server refuses.
…already wide On SQL Server the authuser and user-auth-context widenings drop the unique index on the columns they alter and recreate it as a plain one. On a table the changelog built the columns are already at the target width, so they now record themselves run and change nothing, and (username, provider) stays unique.
The SQL Server arms of the column widenings altered NVARCHAR columns back to VARCHAR, which holds only the database's code page. They now keep NVARCHAR, as the Mapper driver created and as the role-name and metric widenings already did.
Oracle stores '' as NULL, so a system-level Role, whose bank id is the empty string, was never found there. On Oracle the pool's connections are now wrapped: an empty string bound to a statement is written as CHR(0), CHR(0) read back is returned as "", and an empty literal '' in the SQL text becomes CHR(0). The other databases are not wrapped.
Oracle refuses AS before a table alias, so pruning the run log failed there, and the scheduler's second attempt to record the run then hit the run id's unique index.
The attribute queries compare the value with =, and Oracle cannot compare a CLOB, which is what the unbounded text type is there. An attribute.value.type property makes it VARCHAR2(4000) on Oracle and the same unbounded type as before elsewhere, so no other database's checksum moves.
…racle Liquibase takes PASSWORD for a reserved word on Oracle and created the column as "password", which an unquoted reference, folded to PASSWORD, never finds. An Oracle-only changeset renames it to PASSWORD. The precondition check now accepts a renameColumn guarded by a sqlCheck.
…ady in place The migration adds mappedconsent.consent_reference_id to a database that predates it. On a table the changelog built the column and its unique index are already there, and on SQL Server the migration dropped that index and enforced uniqueness with a constraint of another name. It now records itself run and changes nothing there.
…ite intact Scala's StringBuilder has no append(String, Int, Int), so the call appended the three arguments as a tuple, and a statement holding a quoted identifier or a comment next to an empty literal came out garbled. OracleEmptyStringsTest caught it.
Liquibase creates DOUBLE as a decimal type on Oracle, and a double written to it came back rounded to 15 significant digits, so a stored location did not read back as written. A Liquibase data type registered for Oracle alone creates BINARY_DOUBLE, the IEEE 754 double the other databases store. The changelog is unchanged.
On Oracle the url names only the service, so the scenario that the configured database is disposable has to pass the user the suite logs in as, which TestServer's guard does.
Random.nextString can end a value in a control character, which the routing's trim removes, so the value read back differed from the one sent whenever the last character drawn was one. The routings are now random text without control characters or spaces.
The Oracle driver binds a double as a decimal NUMBER by default, keeping about 15 significant digits, so a location written to a BINARY_DOUBLE column still came back rounded. SetFloatAndDoubleUseBinary makes it send the IEEE 754 value.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Migrates OBP-API to Scala 3, replacing the two frameworks that blocked it. 287 commits on top of
3df73fe11; 1027 files, +66009/-33154.Opened for review of the whole line. It does not merge cleanly onto
developyet — the branchis 26 commits behind and conflicts in 12 files, all of them where
developextended a Lift Mapperentity this branch had already moved to Doobie. That merge is in progress separately and will be
pushed here; the conflicts are listed at the end so reviewers know what is coming rather than
discovering it from a red merge box.
What changed
Scala 3. Lift Mapper cannot compile under Scala 3 — the compiler crashes on the
object X extends class Xshape every Mapper entity uses (reduced to a 5-line case). Both of itsconsumers had to go first.
Lift Web → http4s, complete.
net.liftweb.httpno longer appears in any.scalasource. Thereis no Lift fallback in the request chain: an unmatched
/obp/*path returns a JSON 404 fromnotFoundCatchAll. API versions are unchanged by this — a framework migration happens in placeinside the existing version file, and a version bump still means a changed API signature.
Lift Mapper → Doobie, complete.
ToSchemify.modelsis nowNil; Schemifier creates nothing.Flyway → Liquibase. Flyway needed one hand-written script set per vendor: 118 for H2, 118 for
Postgres, and nothing for the three other drivers its
vendorFolderwould have booted againstsilently, with no tables. One changelog now describes each change once and Liquibase emits the
dialect. The baseline is generated from a Postgres database the Flyway scripts built, not
hand-written, and is regenerated with
scripts/GenerateChangelog.javaplus a normaliser ratherthan edited.
Defects found and fixed along the way
Migrating the data layer surfaced behaviour that lived in Mapper's field types rather than in the
entities, and which a column-by-column port drops silently:
MappedBooleanreads back asfalsewhateverdefaultValuedeclares, a NULLMappedLongas the declared default — read as a hardcoded-1, six call-limit columns turned"the configured limit" into "no limit", and that value is what the rate limiter enforces from
MappedEmaillowercases and trims on every set and validates on save;authuserlost all of itMappedMetrics, reachable from read-only roles, giving a boolean-blindoracle over the whole database
Security fixes on top: a locked account could still authenticate through OIDC and Keycloak (both
read
v_oidc_usersover JDBC and never callverify-credentials);consents.sca.enabled=falseaccepted any SCA answer in production; the dynamic-code dependency validation inspected an empty
list because its scan was gated on an unrelated diagnostic prop; and
compileScalaCodenow refusesto run when no SecurityManager can be installed (JEP 486) unless the operator says so explicitly.
Testing
3876 scenarios, 0 failures, on both H2 and Postgres. Postgres is not optional here: H2 tolerates
things Postgres does not, and the schema is generated from the changelog at boot on both.
Conflicts with current develop
developaddedcreatedByUserId/updatedByUserId/ a method-body hash to DynamicResourceDoc,DynamicMessageDoc and ConnectorMethod, and one new Mapper entity (
ChatEmailDigestState). Thisbranch had already moved the first three to Doobie, so the resolution ports the new fields into the
Doobie stores and the changelog rather than restoring the Mapper entities;
ChatEmailDigestStateneeds the same treatment, since with
models = Nilits table would otherwise never be created.