# Many apps in one project

Source: https://dabadata.com/docs/many-apps/ (HTML) - https://dabadata.com/docs/many-apps/index.md (this page as markdown)

One project can hold several apps that share some of their data: two games and the coin wallet they both pay from, a shop and its loyalty points. Each app keeps its own tables and actions under a prefix, the shared tables keep their plain names, and the whole is one definition. Bobi Coin, an example in the repository, runs a hub and two card games this way with one wallet and one sign-in, and with no worker: machine opponents are the server's random picks, and results are computed in the browser and checked by the server. Composing is not a platform feature: a definition is plain data, so putting apps together is merging their parts before you apply them.

## Why one project

- **Value moves in one transaction.** An action runs in one transaction inside one environment. When the game and the wallet are in the same project, taking a stake, dealing the cards and opening the pot either all happen or none do. Across two projects there is no transaction: you would need a trusted relay holding two keys, and code to undo half a transfer when the other half fails.
- **One user base.** A person has one account and one user id in every app of the project, so a rule or an action can relate a row of one app to a row of another (a player's one live match, whatever the game).
- **One sign-in** when the apps are served from one origin ([below](https://dabadata.com/docs/many-apps/index.md#site)).

The cost: one definition, so every app's change is applied together; one plan, one set of [limits](https://dabadata.com/docs/limits/index.md) and one trace for all of them; one namespace of names and roles. Keep apps in separate projects when they share no data, belong to different teams, or must be isolated from each other.

## Modules: one part per app, with a prefix

Write each app's part of the definition as a function of its prefix. Every name the app owns - tables, views, actions, buckets, webhooks, schedules - gets the prefix; the shared tables are named plainly:

```ts
export function duelModule(prefix = "") {
  const n = (name: string) => prefix + name;           // "duel_" + "matches" = "duel_matches"
  return {
    roles: ["player", "admin"],                          // shared roles are listed by every part
    tables: {
      [n("matches")]: { columns: { player_a: t.userId(), player_b: t.userId(), pot: t.int({ default: 0 }) },
                        checks: { pot_not_negative: "pot >= 0" }, rules: { ... } },
      [n("rounds")]:  { ... },
    },
    actions: {
      [n("accept_match")]: { allow: "authenticated", steps: [ ... ] },   // reads and writes "players", "ledger"
      [n("play_machine")]: { allow: "authenticated", steps: [ ... ] },   // the machine's moves are server fills
    },
  };
}
```

- The same module with the prefix `""` plus the shared parts is the app as a project of its own. That is how each game of Bobi Coin is developed and tested alone.
- Table names are at most 41 characters ([Names](https://dabadata.com/docs/tables/index.md#names)), prefix included; keep prefixes short (`kid_`, `war_`).
- The app's pages need the prefix too (and its worker, if it has one). Bobi Coin's pages read it from a meta tag (`<meta name="kidnapper-prefix" content="kid_">`), so the same files serve the app alone and inside the project.

Then merge the parts into one definition and apply it as usual (`dabadata push`, `PUT /v1/schema`). `compose()` in `examples/bobicoin/wallet.ts` is about 30 lines: it unites the roles and merges tables, views, actions, buckets, webhooks and schedules, and throws when two parts declare the same name, so a missing prefix is caught before anything is applied:

```ts
import { compose, wallet } from "./wallet.ts";

export default compose("bobicoin", [
  wallet(),                                    // players, ledger, wallet_settings; join, claim_welcome, claim_daily
  kidnapperModule("kid_"),                     // kid_matches, kid_rounds, kid_choose_card, ...
  warcallModule("war_"),                       // war_matches, war_choices, ...
], { auth: { users: { enabled: true, defaultRole: "player" } } });
```

## One shared wallet

The shared part owns the balance. In Bobi Coin it is three tables and four actions:

- `players`: one row per person, its id the user id; `coins` with a check `coins >= 0`; win, loss and draw totals across games; `live_match` ([below](https://dabadata.com/docs/many-apps/index.md#live-match)). Clients may change only their own name and picture; `coins` has no client write rule at all.
- `ledger`: one row per movement - player, game, match, amount (never negative), `out`, reason (`welcome`, `daily`, `stake`, `win`, `refund`).
- `wallet_settings`: the starting and daily coins, as rows an admin edits.
- `join` makes the player row; `claim_welcome` pays the starting coins once (`expect: { welcomed: false }`); `claim_daily` pays once per UTC day (`expect: { daily_on: { $ne: "$now" } }`).

A game moves coins inside its own actions, in the same transaction as the game's own rows. Accepting a match takes both stakes, records them, deals and opens the pot; any failed `expect` or check rolls all of it back:

```json
"kid_accept_match": {
  "allow": "authenticated",
  "params": { "match": { "type": "ref", "table": "kid_matches" } },
  "steps": [
    { "op": "check", "table": "kid_matches", "id": "$params.match", "ref": "m",
      "expect": { "player_b": "$user.id", "status": "invited", "deadline": { "$gt": "$now" } } },
    { "op": "update", "table": "players", "id": "$step.m.player_a",
      "expect": { "coins": { "$gte": "$step.m.escrow" }, "live_match": null },
      "values": { "coins": { "$dec": "$step.m.stake" }, "live_match": "$params.match", "live_game": "kidnapper" } },
    { "op": "update", "table": "players", "id": "$user.id",
      "expect": { "coins": { "$gte": "$step.m.escrow" }, "live_match": null },
      "values": { "coins": { "$dec": "$step.m.stake" }, "live_match": "$params.match", "live_game": "kidnapper" } },
    { "op": "insert", "table": "ledger", "values": { "game": "kidnapper", "player": "$step.m.player_a", "match": "$params.match", "amount": "$step.m.stake", "reason": "stake", "out": true } },
    { "op": "insert", "table": "ledger", "values": { "game": "kidnapper", "player": "$user.id", "match": "$params.match", "amount": "$step.m.stake", "reason": "stake", "out": true } },
    { "op": "draw", ... },
    { "op": "update", "table": "kid_matches", "id": "$params.match",
      "values": { "status": "active", "pot": "$step.m.pair", "jackpot": "$step.m.pair" } }
  ]
}
```

Each later round takes the next stakes the same way, and every payout comes out of the match's `pot`, which a check keeps at zero or above and the last settlement empties exactly. So coins are never created by a game: they only move between players and pots, and the house pays only through the actions that say so: against the machine, the house's share goes into the pot each round (from a table only admins write), and a win pays the pot, never an amount the client sends ([a machine opponent with no backend](https://dabadata.com/docs/turn-based/index.md#machine)). Action steps run with the server's rights, so a game that moves coins only through its actions needs no write rule on the wallet.

## One live match across apps

`players.live_match` holds the match a person is playing, in any game, and `live_game` which game it is. A game sets it when a match starts, with `expect: { live_match: null }`, so nobody can be in two matches of any two games; it charges each later stake with `expect: { live_match: "$params.match" }`, so coins are taken only for the match the player is in; and it clears it at the end. Bobi Coin's hub reads it to show how many players are in a match in each game.

## Roles and workers per app

Bobi Coin's games need no worker: their machine opponents are the server's random picks, and the player's browser computes each result, which the server checks and caps by the match's pot ([a machine opponent with no backend](https://dabadata.com/docs/turn-based/index.md#machine)). The worker points below apply only to an app that needs trusted logic of its own ([Background workers](https://dabadata.com/docs/workers/index.md)).

- **Shared roles** (`player`, `admin`) are declared by every part; `compose()` keeps each once.
- **Each app's worker has its own role** (`duel_worker`, `shop_worker`), its own hosted user and its own queue. A leaked password of one app's worker reaches only the actions of that role.
- **Prefer actions to write rules.** A worker that writes coins only through its app's actions needs nothing from the wallet. One that writes balances directly must be named in the wallet's `workerRoles`, which gives that role update on `players` and insert on `ledger` - more than an action would.
- **Subscribe to your own tables.** A worker subscribes to its prefixed tables only, with a `where` for what it acts on, and ignores events of other prefixes. Several apps' workers can share one Redis with a queue each ([Deploying a worker stack](https://dabadata.com/docs/workers/index.md#deploy)).

## One site, one sign-in

Serve every app of the project from one [site](https://dabadata.com/docs/sites/index.md), each under its own path: Bobi Coin is `https://bobicoin.dabadata.site/` (the hub), `/kidnapper/` and `/warcall/`. The JavaScript client keeps a signed-in session in `localStorage` under the API's URL and the publishable key ([Where the session is kept](https://dabadata.com/docs/client/index.md#storage)), and `localStorage` belongs to one origin. So every page of one origin with the same key shares the session: sign in on the hub, and the games know you. Apps on separate subdomains would each need their own sign-in. List every page that sign-in may return to in `auth.users.redirectUrls`. Publishing such a site: [Sites: many apps under paths](https://dabadata.com/docs/sites/index.md#many-apps).

## Bobi Coin in the repository

| File | What |
| --- | --- |
| `examples/bobicoin/bobicoin.ts` | The composed definition: the wallet, `kidnapperModule("kid_")`, `warcallModule("war_")`, sign-in, the redirect URLs |
| `examples/bobicoin/wallet.ts` | `wallet()` (the shared tables and actions) and `compose()` |
| `examples/bobicoin/prefixes.ts` | Each game's prefix, read by the site builder |
| `examples/kidnapper/kidnapper.ts`, `examples/warcall/warcall.ts` | The game modules |
| `examples/bobicoin/ops/` | `create-prod.ts` (the project and its default rows), `build-site.ts` and `publish-site.ts` (the one site) |
| `examples/bobicoin/worker-kit/`, `examples/bobicoin/deploy/` | An example worker kit and worker stack, kept as an example of the pattern; Bobi Coin's games do not use them ([Background workers](https://dabadata.com/docs/workers/index.md)) |

What each game demonstrates: [Examples](https://dabadata.com/docs/examples/index.md#bobicoin).
