@duraxis/nestjs 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,4 +1,17 @@
1
1
  # @duraxis/nestjs changelog
2
2
 
3
+ ## 0.1.2
4
+
5
+ ### Patch Changes
6
+
7
+ - a447bb5: Activate declarative transactions automatically for standard Nest class providers using application-scoped property injection. Preserve provider identity and support singleton, transient and request scopes, lifecycle calls after injection, inherited metadata and self-invocation. Deprecate the transactional registration helpers while retaining their named-connection defaults for migration. Self-invocation now honors inner transaction boundaries; constructor-time transactions remain unsupported and are documented explicitly.
8
+
9
+ ## 0.1.1
10
+
11
+ ### Patch Changes
12
+
13
+ - 0b272bd: Improve disk storage ownership recovery and NestJS lifecycle management to safely handle abandoned locks and application restarts
14
+ - @duraxis/orm@0.1.0
15
+
3
16
  This file is maintained by Changesets. Future releases will add versioned
4
17
  entries automatically.
package/README.md CHANGED
@@ -50,8 +50,9 @@ class UserService {
50
50
  entities: [User],
51
51
  schema: { mode: "create" },
52
52
  }),
53
- DuraxisModule.forTransactionalFeature([User], [UserService]),
53
+ DuraxisModule.forFeature([User]),
54
54
  ],
55
+ providers: [UserService],
55
56
  })
56
57
  export class AppModule {}
57
58
  ```
@@ -74,8 +75,8 @@ DuraxisModule.forRootAsync({
74
75
  });
75
76
  ```
76
77
 
77
- Com `autoLoadEntities: true`, entidades declaradas por `forFeature` ou
78
- `forTransactionalFeature` para a mesma conexão são agregadas durante a inicialização. Sem essa
78
+ Com `autoLoadEntities: true`, entidades declaradas por `forFeature` para a mesma conexão são
79
+ agregadas durante a inicialização. Sem essa
79
80
  opção, elas também devem constar em `entities` no root.
80
81
 
81
82
  ## Injeção e transações
@@ -83,13 +84,63 @@ opção, elas também devem constar em `entities` no root.
83
84
  As APIs públicas incluem `InjectDuraxisRepository`, `InjectDuraxisOrm`,
84
85
  `InjectDuraxisDatabase`, `InjectDuraxisTransactionManager` e seus geradores de token.
85
86
 
86
- `@Transactional()` é aplicado por proxy: registre o provider com
87
- `forTransactionalFeature(entities, providers)` ou
88
- `forTransactionalProviders(providers)`. Métodos transacionais devem retornar `Promise`. A API
87
+ `@Transactional()` funciona automaticamente em classes registradas no array `providers` de
88
+ `@Module()`. Use apenas `forFeature([Entity])` para disponibilizar os repositórios; nenhum registro
89
+ transacional adicional é necessário. A instância criada pelo Nest mantém sua identidade e injeção
90
+ de dependências. Chamadas por controllers, outros serviços e `this.metodo()` passam pelo mesmo
91
+ limite transacional, inclusive em providers singleton, transient e request-scoped.
92
+
93
+ O decorator também pode ser aplicado à classe. Metadados de classe são herdados e as opções do
94
+ método prevalecem sobre as da classe. Métodos herdados preservam seus decorators; ao substituir
95
+ um método com decorator de método em uma subclasse, reaplique o decorator na nova implementação.
96
+ Métodos transacionais devem retornar `Promise`. A API
89
97
  implementa propagação `REQUIRED`, `REQUIRES_NEW`, `SUPPORTS`, `MANDATORY`, `NOT_SUPPORTED` e
90
98
  `NEVER`; `NESTED`, timeout e níveis além de `DEFAULT`/`SNAPSHOT` são rejeitados. `readOnly`,
91
99
  `rollbackFor` e `noRollbackFor` também estão disponíveis.
92
100
 
101
+ Para conexões nomeadas, declare `@Transactional({ connectionName: "primary" })` no método ou na
102
+ classe e use o mesmo nome na injeção do repositório. Sem essa opção, a conexão é `default`;
103
+ `forFeature([Entity], "primary")` não altera a conexão padrão do decorator.
104
+
105
+ Uma exceção que sai de um limite `REQUIRED` participante marca a transação compartilhada como
106
+ rollback-only, salvo exclusão pelas regras de rollback. Capturá-la no chamador não remove essa
107
+ marca. Uma exceção capturada inteiramente dentro de um único método não chega ao gerenciador.
108
+ `noRollbackFor` permite commit somente para erros correspondentes e nunca anula rollback-only.
109
+
110
+ ### Inicialização e limites
111
+
112
+ A ligação com o gerenciador usa injeção de propriedade do Nest antes dos hooks de inicialização.
113
+ Chamadas a métodos transacionais em `onModuleInit` e `onApplicationBootstrap` são suportadas,
114
+ inclusive antes de `app.init()` quando o provider já terminou a injeção. Hooks não são incluídos
115
+ implicitamente pelo decorator de classe; podem receber `@Transactional()` explicitamente.
116
+
117
+ Não execute trabalho transacional em construtores ou inicializadores de campos. Antes da injeção,
118
+ métodos já decorados lançam `TransactionalProviderNotReadyError`; novos métodos/overrides de uma
119
+ subclasse com apenas metadados de classe herdados e funções de instância só recebem wrappers
120
+ ao terminar a construção. Essas chamadas durante a construção podem escapar da interceptação.
121
+ Não há promessa de interceptação completa durante a construção, nem garantia de disponibilidade
122
+ do gerenciador em factories de inicialização ou construtores de outros providers.
123
+
124
+ Use providers de classe (`providers: [Service]` ou `useClass`). Instâncias criadas manualmente,
125
+ `useValue` e resultados de `useFactory` não recebem injeção de propriedades do Nest; métodos
126
+ decorados falham explicitamente quando invocados sem essa ligação. Nessas instâncias, novos
127
+ métodos/overrides de subclasses com apenas metadados de classe herdados e funções de instância
128
+ permanecem sem wrappers e podem escapar da interceptação. Getters, setters, métodos
129
+ estáticos e substituição de métodos após a injeção não são suportados. Ao desligar, o gerenciador
130
+ aguarda transações em andamento e rejeita novas transações; depois de remover a conexão, chamadas
131
+ decoradas falham com `TransactionManagerNotFoundError`.
132
+
133
+ ### Migração
134
+
135
+ `forTransactionalFeature(entities, providers, connectionName)` e
136
+ `forTransactionalProviders(providers, connectionName)` estão depreciados e continuam disponíveis
137
+ para migração. Troque-os por `forFeature(entities, connectionName)` e mova os serviços para
138
+ `providers` do módulo consumidor. Para conexões nomeadas, explicite `connectionName` no decorator.
139
+ A remoção dos métodos antigos fica para uma versão incompatível futura. Chamadas por `this` agora
140
+ aplicam as opções transacionais do método interno, inclusive propagação e regras de rollback.
141
+
142
+ Veja a [decisão de arquitetura](../../docs/NESTJS_TRANSACTIONS.md) para a análise do ciclo de vida.
143
+
93
144
  Transações declarativas dependem de metadados e inicialização do Nest; o pacote não é marcado
94
145
  como livre de efeitos colaterais. Ele não adiciona coordenação distribuída. Requer Node.js
95
146
  22.12+.
@@ -9,9 +9,6 @@ export interface DuraxisModuleOptions {
9
9
  readonly autoLoadEntities?: boolean;
10
10
  readonly database?: Omit<DuraxisDatabaseOptions, "storage">;
11
11
  readonly schema?: DuraxisOrmOptions["schema"];
12
- /**
13
- * Defaults to true for a driver factory and false for a supplied driver instance.
14
- */
15
12
  readonly closeStorage?: boolean;
16
13
  }
17
14
  export interface DuraxisRootModuleOptions extends DuraxisModuleOptions {
@@ -5,6 +5,8 @@ export declare class DuraxisModule {
5
5
  static forRoot(options: DuraxisRootModuleOptions): DynamicModule;
6
6
  static forRootAsync<TArguments extends readonly unknown[]>(options: DuraxisModuleAsyncOptions<TArguments>): DynamicModule;
7
7
  static forFeature(entities: readonly EntityClass[], connectionName?: string): DynamicModule;
8
+ /** @deprecated Use forFeature(entities, connectionName) and regular module providers. */
8
9
  static forTransactionalFeature(entities: readonly EntityClass[], providers: readonly Type<object>[], connectionName?: string): DynamicModule;
10
+ /** @deprecated Declare services in the consuming module's providers array. */
9
11
  static forTransactionalProviders(providers: readonly Type<object>[], connectionName?: string): DynamicModule;
10
12
  }
package/dist/index.cjs CHANGED
@@ -163,6 +163,11 @@ var TransactionContextManager = class {
163
163
  }
164
164
  };
165
165
  // src/transactions/transaction.errors.ts
166
+ var TransactionalProviderNotReadyError = class extends DuraxisNestError {
167
+ constructor(methodName) {
168
+ super(`Transactional provider ${methodName} is not ready: Nest must complete property injection before invocation. Constructor calls, manual construction, useValue and useFactory instances are unsupported`);
169
+ }
170
+ };
166
171
  var TransactionRequiredError = class extends DuraxisNestError {
167
172
  constructor(connectionName) {
168
173
  super(`An active Duraxis transaction is required for connection ${connectionName}`);
@@ -368,7 +373,7 @@ function transactionAwareBuilder(entity, baseRepository, transactions, captured,
368
373
  } });
369
374
  }
370
375
  function createTransactionAwareRepository(entity, baseRepository, transactions) {
371
- return new Proxy(baseRepository, { get(target, property) {
376
+ return new Proxy(baseRepository, { get(_, property) {
372
377
  if (property == "createQueryBuilder") return () => transactionAwareBuilder(entity, baseRepository, transactions, transactions.currentContext());
373
378
  const effective = transactions.resolveRepository(entity, baseRepository);
374
379
  const value = Reflect.get(effective, property, effective);
@@ -424,7 +429,7 @@ function shouldRollback(error, options) {
424
429
  }
425
430
  for (const constructor of options.noRollbackFor ?? []) {
426
431
  const distance = inheritanceDistance(error, constructor);
427
- if (distance <= bestDistance) {
432
+ if (Number.isFinite(distance) && distance <= bestDistance) {
428
433
  bestDistance = distance;
429
434
  rollback = false;
430
435
  }
@@ -560,6 +565,7 @@ var TransactionManager = class {
560
565
  } catch (error) {
561
566
  await this.rejectPendingOperations(physical);
562
567
  if (error instanceof RollbackOnlyAbort || shouldRollback(error, options)) throw error;
568
+ if (physical.rollbackOnly) throw new RollbackOnlyAbort();
563
569
  return {
564
570
  type: "committed-error",
565
571
  error
@@ -613,26 +619,22 @@ var TransactionManager = class {
613
619
  if (options.connectionName != null) normalizeDuraxisConnectionName(options.connectionName);
614
620
  }
615
621
  };
616
- // src/transactions/transactional.decorator.ts
622
+ // src/transactions/transactional.metadata.ts
617
623
  var TRANSACTIONAL_METADATA = Symbol.for("@duraxis/nestjs/transactional");
618
- function Transactional(options = {}) {
619
- return (target, _propertyKey, descriptor) => {
620
- const metadataTarget = descriptor?.value ?? target;
621
- Reflect.defineMetadata(TRANSACTIONAL_METADATA, Object.freeze({ ...options }), metadataTarget);
622
- };
623
- }
624
- /** Alias of `@Transactional()`. It is unrelated to `Transaction` from `@duraxis/core`. */
625
- var Transaction = Transactional;
626
624
  function transactionalOptions(instance, method) {
627
625
  const classOptions = Reflect.getMetadata(TRANSACTIONAL_METADATA, instance.constructor);
628
626
  const methodOptions = Reflect.getMetadata(TRANSACTIONAL_METADATA, method);
629
- if (!classOptions && !methodOptions) return void 0;
630
- return {
627
+ return !classOptions && !methodOptions ? void 0 : {
631
628
  ...classOptions,
632
629
  ...methodOptions
633
630
  };
634
631
  }
635
- // src/transactions/transactional.proxy.ts
632
+ // src/transactions/transactional.instrumentation.ts
633
+ var MANAGERS = Symbol("Duraxis transaction managers");
634
+ var bindings = /* @__PURE__ */ new WeakMap();
635
+ var defaultConnections = /* @__PURE__ */ new WeakMap();
636
+ var injectablePrototypes = /* @__PURE__ */ new WeakSet();
637
+ var wrappers = /* @__PURE__ */ new WeakSet();
636
638
  var LIFECYCLE_METHODS = /* @__PURE__ */ new Set([
637
639
  "onModuleInit",
638
640
  "onApplicationBootstrap",
@@ -640,28 +642,47 @@ var LIFECYCLE_METHODS = /* @__PURE__ */ new Set([
640
642
  "beforeApplicationShutdown",
641
643
  "onApplicationShutdown"
642
644
  ]);
643
- function createTransactionalServiceProxy(instance, managers, defaultConnectionName) {
644
- const methods = /* @__PURE__ */ new Map();
645
- return new Proxy(instance, { get(target, property) {
646
- const cached = methods.get(property);
647
- if (cached) return cached;
648
- const value = Reflect.get(target, property, target);
649
- if (typeof value != "function") return value;
650
- const options = LIFECYCLE_METHODS.has(property) ? void 0 : transactionalOptions(target, value);
651
- const method = options ? (...arguments_) => {
652
- const connectionName = normalizeDuraxisConnectionName(options.connectionName ?? defaultConnectionName);
653
- return managers.get(connectionName).execute(options, `${target.constructor.name}.${String(property)}`, () => Reflect.apply(value, target, arguments_));
654
- } : value.bind(target);
655
- methods.set(property, method);
656
- return method;
645
+ function injectTransactionManagers(prototype) {
646
+ if (injectablePrototypes.has(prototype)) return;
647
+ injectablePrototypes.add(prototype);
648
+ Object.defineProperty(prototype, MANAGERS, { set(managers) {
649
+ bindings.set(this, managers);
650
+ instrumentTransactionalMethods(this);
657
651
  } });
652
+ (0, _nestjs_common.Inject)(TransactionManagerRegistry)(prototype, MANAGERS);
658
653
  }
659
- function transactionalServiceProvider(service, defaultConnectionName) {
660
- return {
661
- provide: service,
662
- inject: [_nestjs_core.ModuleRef, TransactionManagerRegistry],
663
- useFactory: async (moduleRef, managers) => createTransactionalServiceProxy(await moduleRef.create(service), managers, defaultConnectionName)
654
+ function setTransactionalDefaultConnection(instance, name) {
655
+ defaultConnections.set(instance, name);
656
+ }
657
+ function wrapTransactionalMethod(method, property) {
658
+ if (wrappers.has(method)) return method;
659
+ const wrapped = function(...arguments_) {
660
+ const methodName = `${this.constructor.name}.${String(property)}`;
661
+ const managers = bindings.get(this);
662
+ if (!managers) throw new TransactionalProviderNotReadyError(methodName);
663
+ const options = transactionalOptions(this, wrapped) ?? {};
664
+ const name = normalizeDuraxisConnectionName(options.connectionName ?? defaultConnections.get(this));
665
+ return managers.get(name).execute(options, methodName, () => Reflect.apply(method, this, arguments_));
664
666
  };
667
+ for (const key of Reflect.getOwnMetadataKeys(method)) Reflect.defineMetadata(key, Reflect.getOwnMetadata(key, method), wrapped);
668
+ wrappers.add(wrapped);
669
+ return wrapped;
670
+ }
671
+ function instrumentTransactionalMethods(target) {
672
+ const visited = /* @__PURE__ */ new Set();
673
+ for (let prototype = target; prototype && prototype != Object.prototype; prototype = Object.getPrototypeOf(prototype)) for (const property of Reflect.ownKeys(prototype)) {
674
+ if (visited.has(property)) continue;
675
+ visited.add(property);
676
+ if (property == "constructor" || LIFECYCLE_METHODS.has(property)) continue;
677
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, property);
678
+ const method = descriptor?.value;
679
+ if (typeof method != "function" || !transactionalOptions(target, method)) continue;
680
+ if (wrappers.has(method)) continue;
681
+ Object.defineProperty(target, property, {
682
+ ...descriptor,
683
+ value: wrapTransactionalMethod(method, property)
684
+ });
685
+ }
665
686
  }
666
687
  // src/duraxis.module.ts
667
688
  function rootProviders(name, optionsProvider) {
@@ -738,7 +759,20 @@ function featureModule(entities, services, connectionName) {
738
759
  const uniqueEntities = [...new Set(entities)];
739
760
  const uniqueServices = [...new Set(services)];
740
761
  const repositoryProviders = uniqueEntities.map((entity) => repositoryProvider(entity, name));
741
- const serviceProviders = uniqueServices.map((service) => transactionalServiceProvider(service, name));
762
+ const serviceProviders = uniqueServices.flatMap((service) => {
763
+ return [{
764
+ provide: service,
765
+ useClass: service,
766
+ scope: _nestjs_common.Scope.DEFAULT
767
+ }, {
768
+ provide: Symbol(`${service.name} default transaction connection`),
769
+ inject: [service],
770
+ useFactory: (instance) => {
771
+ setTransactionalDefaultConnection(instance, name);
772
+ return name;
773
+ }
774
+ }];
775
+ });
742
776
  let DuraxisFeatureEntitiesMarker = class DuraxisFeatureEntitiesMarker {};
743
777
  DuraxisFeatureEntitiesMarker = __decorate([DuraxisFeatureEntities({
744
778
  connectionName: name,
@@ -788,9 +822,11 @@ var DuraxisModule = class DuraxisModule {
788
822
  static forFeature(entities, connectionName) {
789
823
  return featureModule(entities, [], connectionName);
790
824
  }
825
+ /** @deprecated Use forFeature(entities, connectionName) and regular module providers. */
791
826
  static forTransactionalFeature(entities, providers, connectionName) {
792
827
  return featureModule(entities, providers, connectionName);
793
828
  }
829
+ /** @deprecated Declare services in the consuming module's providers array. */
794
830
  static forTransactionalProviders(providers, connectionName) {
795
831
  return featureModule([], providers, connectionName);
796
832
  }
@@ -809,6 +845,21 @@ function InjectDuraxisDatabase(connectionName) {
809
845
  function InjectDuraxisTransactionManager(connectionName) {
810
846
  return (0, _nestjs_common.Inject)(getDuraxisTransactionManagerToken(connectionName));
811
847
  }
848
+ // src/transactions/transactional.decorator.ts
849
+ function Transactional(options = {}) {
850
+ return (target, _propertyKey, descriptor) => {
851
+ const metadataTarget = descriptor?.value ?? target;
852
+ Reflect.defineMetadata(TRANSACTIONAL_METADATA, Object.freeze({ ...options }), metadataTarget);
853
+ if (descriptor && _propertyKey != null) {
854
+ if (typeof descriptor.value != "function" || typeof target == "function") throw new TypeError("@Transactional() requires an instance method");
855
+ injectTransactionManagers(target);
856
+ descriptor.value = wrapTransactionalMethod(descriptor.value, _propertyKey);
857
+ } else if (typeof target == "function") {
858
+ injectTransactionManagers(target.prototype);
859
+ instrumentTransactionalMethods(target.prototype);
860
+ }
861
+ };
862
+ }
812
863
  exports.DEFAULT_DURAXIS_CONNECTION = DEFAULT_DURAXIS_CONNECTION;
813
864
  exports.DuplicateDuraxisConnectionError = DuplicateDuraxisConnectionError;
814
865
  Object.defineProperty(exports, "DuraxisModule", {
@@ -825,7 +876,6 @@ exports.InjectDuraxisRepository = InjectDuraxisRepository;
825
876
  exports.InjectDuraxisTransactionManager = InjectDuraxisTransactionManager;
826
877
  exports.NestedTransactionNotSupportedError = NestedTransactionNotSupportedError;
827
878
  exports.ReadOnlyTransactionError = ReadOnlyTransactionError;
828
- exports.Transaction = Transaction;
829
879
  exports.TransactionContextClosedError = TransactionContextClosedError;
830
880
  exports.TransactionContextManager = TransactionContextManager;
831
881
  exports.TransactionIsolation = TransactionIsolation;
@@ -836,6 +886,7 @@ exports.TransactionPropagation = TransactionPropagation;
836
886
  exports.TransactionRequiredError = TransactionRequiredError;
837
887
  exports.Transactional = Transactional;
838
888
  exports.TransactionalMethodReturnTypeError = TransactionalMethodReturnTypeError;
889
+ exports.TransactionalProviderNotReadyError = TransactionalProviderNotReadyError;
839
890
  exports.UnawaitedTransactionOperationError = UnawaitedTransactionOperationError;
840
891
  exports.UnexpectedTransactionRollbackError = UnexpectedTransactionRollbackError;
841
892
  exports.UnsupportedMixedTransactionError = UnsupportedMixedTransactionError;