npm package: @glassops/weave
Description: Establishes connections with external services for data persistence, caching, file storage, and transmitting communications.
Author: GlassOps Limited
Latest version: 1.0.0

# Weave

> `@glassops/weave`

Deterministic, multi‑tenant connection weaving for MongoDB, PostgreSQL, Redis, and S3 — with strict identity semantics, retry logic, scoped logging, and lifecycle‑safe registry management.

Weave provides isolated, identity‑scoped service instances instead of global singletons. Every connection is created intentionally, logged explicitly, and registered under a multi‑dimensional identity key: `tenant.service.namespace.environment`.

This ensures contributor‑safe behavior across all GlassOps services, prevents accidental cross‑tenant leakage, and enables deterministic teardown.

## Why Weave exists

Modern backend systems often rely on global singletons, implicit connection reuse, and ad‑hoc retry logic. These patterns break down in:

- Multi‑tenant architectures.
- Regulated environments.
- Distributed service meshes.
- Systems requiring deterministic teardown.
- Environments where connection identity matters (audit, compliance, isolation).

Weave solves this by providing:

- Isolated connections (no global state, no hidden pooling).
- Deterministic retry logic with exponential backoff + jitter.
- Strict identity assignment (tenant, namespace, environment).
- A global registry for lifecycle management.
- Uniform service‑instance wrappers implementing a shared contract.
- Scoped logging via `@glassops/scribe`.

Every connection is explicit, observable, and safe.

## Features

### Deterministic multi‑tenant identity

Each instance is keyed by:

- `tenant`: Who owns the connection.
- `service`: MongoDB, PostgreSQL, Redis, S3.
- `namespace`: `dbName`, `schema`, Redis namespace, S3 bucket.
- `environment`: `dev`, `staging`, `prod`.

Identity is encoded as:

`tenant.service.namespace.environment`

This prevents collisions and enables safe teardown.

### Retry logic with exponential backoff + jitter

All weave functions implement:

- Exponential backoff.
- Bounded jitter.
- Max retry limits.
- Socket/connection timeouts.
- Structured logging for each attempt.

This ensures predictable behavior under load or partial outages.

### Isolated service instances

Each backend has a dedicated wrapper implementing:

```ts
interface BaseServiceInstance {
  id: string;
  key: RegistryKey;
  service: ServiceType;
  connectedAt: Date;
  close(): Promise<void>;
  healthCheck?(): Promise<boolean>;
}
```

No global singletons. No hidden pooling. No shared state.

### Global service registry

Weave maintains a deterministic registry:

- `register`
- `deregister`
- `list`
- `closeAll`

All keyed by the composite identity.

This enables:

- Safe teardown.
- Tenant‑scoped cleanup.
- Environment‑scoped cleanup.
- Introspection for operator tooling.

### Uniform weave functions

Each backend has a deterministic connection factory:

- `weaveMongo`
- `weavePostgreSql`
- `weaveRedis`
- `weaveS3`

All follow the same signature:

`weaveX(uri, tenant, namespace, environment, logger, options)`

## Installation

```ts
npm install @glassops/weave
```

## Quick Start

1. Create a ServiceManager:

    ```ts
    import { ServiceManager } from '@glassops/weave';
    import { createLogger } from '@glassops/scribe';

    const logger = createLogger({ service: 'my-service' });
    const services = new ServiceManager(logger);
    ```

2. Connect to MongoDB:

    ```ts
    const mongo = await services.connectMongo(
        process.env.MONGO_URI!,
        'tenantA',
        'users-db',
        'prod',
        { maxRetries: 5 }
    );
    ```

3. Connect to PostgreSQL:

    ```ts
    const pg = await services.connectPostgreSQL(
        process.env.PG_URI!,
        'tenantA',
        'analytics',
        'prod'
    );
    ```

4. Connect to Redis:

    ```ts
    const redis = await services.connectRedis(
    process.env.REDIS_URI!,
    'tenantA',
    'cache',
    'prod'
    );
    ```

5. Connect to S3:

    ```ts
    const s3 = await services.connectS3(
    'my-bucket',
    'tenantA',
    { region: 'us-west-2' },
    'prod'
    );
    ```

6. List active instances:

    ```ts
    const redisInstances = services.list('Redis');
    ```

7. Gracefully shut down everything:

    ```ts
    await services.closeAll();
    ```

## Identity Model

Every service instance carries a RegistryKey:

```ts
interface RegistryKey {
  tenant: string;
  service: ServiceType;
  namespace?: string;
  environment?: string;
}
```

This is encoded into a deterministic ServiceRegistryKey: `tenant.service.namespace.environment`.

Used internally for:

- Uniqueness enforcement.
- Registry lookups.
- Teardown.
- Operator tooling.
- Audit trails.

## Weave Functions

### MongoDB

```ts
weaveMongo(
    mongoUri,
    tenant,
    dbName,
    environment,
    logger,
    options
)
```

Creates an isolated Mongoose connection with retry logic.

### PostgreSQL

```ts
weavePostgreSql(
  connectionString,
  tenant,
  namespace,
  environment,
  logger,
  options
)
```

Creates a deterministic connection pool with health checks.

### Redis

```ts
weaveRedis(
  redisUri,
  tenant,
  namespace,
  environment,
  logger,
  options
)
```

Creates an isolated Redis client with ping‑based health checks.

### S3

```ts
weaveS3(
  bucket,
  tenant,
  environment,
  logger,
  options
)
```

Verifies bucket access and returns an identity‑scoped S3 client.

## Service Registry

Weave exposes a global registry for introspection and lifecycle control:

```ts
registerServiceInstance(instance)
deregisterServiceInstance(instance)
listServiceInstances(serviceType)
closeAllServiceInstances()
```

All operations are identity‑driven and deterministic.

## ServiceManager

A high‑level orchestrator that wraps all weave functions and registry operations:

```ts
const services = new ServiceManager(logger);

await services.connectMongo(...);
await services.connectPostgreSQL(...);
await services.connectRedis(...);
await services.connectS3(...);

services.list('MongoDB');
await services.closeAll();
```

## Design Principles

- **Determinism over convenience**: No global singletons. No implicit pooling. No hidden state.
- **Identity over instance**: Every connection is tied to a tenant, namespace, and environment.
- **Safety over magic**: Registry operations are explicit and validated.
- **Observability everywhere**: All weave functions emit structured logs using `@glassops/scribe`.
- **Uniformity across backends**: Every service follows the same lifecycle contract.

## When to use Weave

Use Weave when you need:

- Multi‑tenant backend connections.
- Deterministic teardown.
- Strict identity semantics.
- Retry logic with jitter.
- Isolated service instances.
- Platform‑level lifecycle management.
- Operator‑safe introspection.

## When not to use Weave

Avoid Weave if:

- You want global singletons.
- You don’t need multi‑tenant isolation.
- You prefer implicit connection reuse.
- You don’t need deterministic teardown.

## License

Copyright [2026] [GlassOps Limited]

Licensed under the Apache License, Version 2.0 (["License"](LICENSE)).

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.